正则表达式:如何删除Perl中字符串之间的额外空格

前端之家收集整理的这篇文章主要介绍了正则表达式:如何删除Perl中字符串之间的额外空格前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在开发一个程序,用于输入两个文件名的用户输入.不幸的是,如果用户不遵循指定的输入格式,程序很容易中断.我想编写代码来提高它对这些类型的错误的弹性.当你看到我的代码时,你会明白的:
# Ask the user for the filename of the qseq file and barcode.txt file
print "Please enter the name of the qseq file and the barcode file separated by a comma:";
# user should enter filenames like this: sample1.qseq,barcode.txt

# remove the newline from the qseq filename
chomp ($filenames = <STDIN>);

# an empty array
my @filenames;

# remove the ',' and put the files into an array separated by spaces; indexes the files
push @filename,join(' ',split(',',$filenames))

# the qseq file
my $qseq_filename = shift @filenames;

# the barcode file.
my barcode = shift @filenames;

显然,如果用户输入错误类型的文件名(.tab文件而不是.txt或.seq而不是.qseq),此代码运行可能会遇到错误.我想要能够进行某种检查的代码,看看用户输入了适当的文件类型.

另一个可能破坏代码错误用户文件名之前输入太多空格.例如:sample1.qseq,(这里想象6个空格)barcode.txt(注意逗号后面的空格很多)

另一个例子:(想象这里有6个空格)sample1.qseq,barcode.txt(这次注意第一个文件名之前的空格数)

我还想要一行代码可以删除额外的空格,以便程序不会中断.我认为用户输入必须采用以下格式:sample1.qseq,barcode.txt.用户输入必须采用这种格式,以便我可以正确地将文件名索引到一个数组中,然后将它们移出.

感谢任何帮助或建议,非常感谢!

解决此类问题的标准方法是使用命令行选项,而不是从STDIN收集输入. Getopt::Long附带Perl并且可以使用:
use strict; use warnings FATAL => 'all';
use Getopt::Long qw(GetOptions);
my %opt;
GetOptions(\%opt,'qseq=s','barcode=s') or die;
die <<"USAGE" unless exists $opt{qseq} and $opt{qseq} =~ /^sample\d[.]qseq$/ and exists $opt{barcode} and $opt{barcode} =~ /^barcode.*\.txt$/;
Usage: $0 --qseq sample1.qseq --barcode barcode.txt
       $0 -q sample1.qseq -b barcode.txt
USAGE
printf "q==<%s> b==<%s>\n",$opt{qseq},$opt{barcode};

shell将处理任何无关的空白,尝试并查看.您需要对文件名进行验证,我在示例中使用了正则表达式.使用Pod::Usage以更好的方式将有用的文档输出给可能导致调用错误用户.

CPAN上有许多更先进的Getopt模块.

原文链接:https://www.f2er.com/regex/356736.html

猜你在找的正则表达式相关文章