Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I combine Perl's split command with white space trimming?

Tags:

split

perl

Repost from Perlmonks for a coworker:

I wrote a perl script to separate long lists of email separated by a semi colon. What I would like to do with the code is combine the split with the trimming of white space so I don't need two arrays. Is there away to trim while loading the first array. Output is a sorted list of names. Thanks.

#!/pw/prod/svr4/bin/perl
use warnings;
use strict;

my $file_data =
  'Builder, Bob  ;Stein, Franklin MSW; Boop, Elizabeth PHD   Cc: Bear,
+ Izzy';
my @email_list;

$file_data =~ s/CC:/;/ig;
$file_data =~ s/PHD//ig;
$file_data =~ s/MSW//ig;

my @tmp_data = split( /;/, $file_data );

foreach my $entry (@tmp_data) {
    $entry =~ s/^[ \t]+|[ \t]+$//g;
    push( @email_list, $entry );
}

foreach my $name ( sort(@email_list) ) {
    print "$name \n";
}
like image 900
Shawn Craver Avatar asked Nov 28 '22 05:11

Shawn Craver


1 Answers

You don't have to do both operations in one go using the same function. Sometimes performing the actions separately can be more clear. That is, split first, then strip the whitespace off of each element (and then sort the result):

@email_list =
    sort(
        map {
                s/\s*(\S+)\s*/\1/; $_
            }
            split ';', $file_data
    );

EDIT: Stripping more than one part of a string at the same time can lead to pitfalls, e.g. Sinan's point below about leaving trailing spaces in the "Elizabeth" portion. I coded that snippet with the assumption that the name would not have internal whitespace, which is actually quite wrong and would have stood out as incorrect if I had consciously noticed it. The code is much improved (and also more readable) below:

@email_list =
    sort(
        map {   
                s/^\s+//;  # strip leading spaces
                s/\s+$//;  # strip trailing spaces
                $_         # return the modified string
            }
            split ';', $file_data
    );
like image 192
Ether Avatar answered Dec 04 '22 16:12

Ether