Regex: How to remove extra spaces between strings in Perl

前端 未结 5 444
不知归路
不知归路 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:28

    First, put use strict; at the top of your code and declare your variables.

    Second, this:

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

    Is not going to do what you want. split() takes a string and turns it into an array. Join takes a list of items and returns a string. You just want to split:

    my @filenames = split(',', $filenames);
    

    That will create an array like you expect.

    This function will safely trim white space from the beginning and end of a string:

    sub trim {
        my $string = shift;
        $string =~ s/^\s+//;
        $string =~ s/\s+$//;
        return $string;
    }
    

    Access it like this:

    my $file = trim(shift @filenames);
    

    Depending on your script, it might be easier to pass the strings as command line arguments. You can access them through the @ARGV array but I prefer to use GetOpt::Long:

    use strict;
    use Getopt::Long;
    Getopt::Long::Configure("bundling");
    
    my ($qseq_filename, $barcode);
    
    GetOptions (
        'q|qseq=s' => \$qseq_filename,
        'b|bar=s'  => \$barcode,
    );
    

    You can then call this as:

    ./script.pl -q sample1.qseq -b barcode.txt
    

    And the variables will be properly populated without a need to worry about trimming white space.

提交回复
热议问题