Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map with Split & Trim in Perl

Tags:

split

trim

map

perl

How do I use map with the split function to trim the constituents: $a, $b, $c and $d; of $line?

my ($a, $b, $c, $d, $e) = split(/\t/, $line);

# Perl trim function to remove whitespace from the start and end of the string
sub trim($)
{
    my $string = shift;
    $string =~ s/^\s+//;
    $string =~ s/\s+$//;
    return $string;
}
like image 488
syker Avatar asked Dec 28 '22 11:12

syker


1 Answers

Don't use prototypes the ($) on your function unless you need them.

my ( $a, $b, $c, $d, $e ) =
  map {s/^\s+|\s+$//g; $_}    ## Notice the `, $_` this is common
  , split(/\t/, $line, 5)
;

Don't forget in the above s/// returns the replacement count -- not $_. So, we do that explicitly.

or more simply:

my @values = map {s/^\s+|\s+$//g; $_}, split(/\t/, $line, 5), $line
like image 155
NO WAR WITH RUSSIA Avatar answered Dec 31 '22 00:12

NO WAR WITH RUSSIA