Values from IF statement regex match (Perl)

if-statement, perl, regex

Solution

A match in list context yields a list of the capture groups. If it fails, it returns an empty list, which is false. You can therefore

if( my ( $val1, $val2, $val3 ) = $line =~ m/^(\S+)\s*(\S+)\s*(\S+)$/ ) {
   ...
}

However, a number of red flags are apparent in this code. That regexp capture looks very similar to a split:

if( my ( $val2, $val2, $val3 ) = split ' ', $line ) {
   ...
}

Secondly, why split $file by linefeeds; if you are reading the contents of a file, far nicer is to actually read a single line at once:

while( my $line = <$fh> ) {
   ...
}

Problem

I'm currently extracting values from a table within a file via REGEX line matches against the table rows. ``` foreach my $line (split("\n", $file)) { if ($line =~ /^(\S+)\s*(\S+)\s*(\S+)$/) { my ($val1, $val2, $val3) = ($1, $2, $3); # $val's used here } } ``` I purposely assign vals for clarity in the code. Some of my table rows contain 10+ vals (aka columns) - is there a more efficient method of assigning the vals instead of doing ... = ($1, $2, ..., $n)?

Original source

Related problems