加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-13 22:56:46 所属栏目:百科 来源:网络整理
导读:我正在开发一个程序,用于输入两个文件名的用户输入.不幸的是,如果用户不遵循指定的输入格式,程序很容易中断.我想编写代码来提高它对这些类型的错误的弹性.当你看到我的代码时,你会明白的: # Ask the user for the filename of the qseq file and barcode.tx
我正在开发一个程序,用于输入两个文件名的用户输入.不幸的是,如果用户不遵循指定的输入格式,程序很容易中断.我想编写代码来提高它对这些类型的错误的弹性.当你看到我的代码时,你会明白的:
# 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} =~ /^sampled[.]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模块.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读