in reply to Re: regex in perl
in thread regex in perl
The original syntax is correct ...
The original syntax may be correct in that it compiles without error, but it is semantically incorrect in that it doesn't actually do anything. grep looks at the truthiness of the evaluated expression or statement block, and a Regexp object alone is always true. Only when evaluated within a match operator can it result in a true or false value. Consider:
c:\@Work\Perl\monks>perl -wMstrict -MData::Dump -le "use Regexp::Common qw /net/; ;; my $records = [ qw(1.2.3.4 12.23.34.45 9.9.9 x.x.x.x anything) ]; ;; my @temp = grep {$RE{net}{IPv4}} @$records; dd \@temp; ;; @temp = grep { m/$RE{net}{IPv4}/ } @$records; dd \@temp; " ["1.2.3.4", "12.23.34.45", "9.9.9", "x.x.x.x", "anything"] ["1.2.3.4", "12.23.34.45"]
Update: The code would also have been semantically correct had it used an explicit binding of $_ to the Regexp object:
c:\@Work\Perl\monks>perl -wMstrict -MData::Dump -le "use Regexp::Common qw /net/; ;; my $records = [ qw(1.2.3.4 12.23.34.45 9.9.9 x.x.x.x anything) ]; ;; my @temp = grep { $_ =~ $RE{net}{IPv4} } @$records; dd \@temp; " ["1.2.3.4", "12.23.34.45"]
Give a man a fish: <%-{-{-{-<
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^3: regex in perl
by BillKSmith (Monsignor) on Jun 16, 2016 at 16:04 UTC |