Regex: How to remove extra spaces between strings in Perl

前端 未结 5 466
不知归路
不知归路 2021-01-18 10:03

I am working on a program that take user input for two file names. Unfortunately, the program can easily break if the user does not follow the specified format of the input.

5条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-18 10:20

    The standard way to deal with this kind of problem is utilising command-line options, not gathering input from STDIN. Getopt::Long comes with Perl and is servicable:

    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};
    

    The shell will deal with any extraneous whitespace, try it and see. You need to do the validation of the file names, I made up something with regex in the example. Employ Pod::Usage for a fancier way to output helpful documentation to your users who are likely to get the invocation wrong.

    There are dozens of more advanced Getopt modules on CPAN.

提交回复
热议问题