in reply to Re^2: Passing variables into regular expressions
in thread Passing variables into regular expressions

So something like:

use strict; use warnings; my $HN = 'fred'; while (<DATA>) { next if ! /^((?:\d{1,3}\.){3}\d{1,3})\s+(\S*)/; next if $HN ne $2; print "$1\n"; print "$2\n"; } __DATA__ 0.0.0.22 fred localhost 0.0.63.23 fred-test-0 1.0.128.24 fred-test-1

Prints:

0.0.0.22 fred

is what you are after? You could do the test in one line or you could interpolate the variable into the regex, but has the advantage of being pretty clean and clear I think.


DWIM is Perl's answer to Gödel

Replies are listed 'Best First'.
Re^4: Passing variables into regular expressions
by Herkum (Parson) on Apr 20, 2006 at 12:48 UTC
    I wanted to make one suggestion, instead of having a pure Regular Expression break it apart and assign it to variables to make it more readable.
    use strict; use warnings; my $IP_ADDRESS = qr{(?:\d{1,3}\.){3}\d{1,3}}xms; my $HOST_NAME = qr{\S*}xms; my $HN = 'fred'; while (<DATA>) { next if ! qr{\A ($IP_ADDRESS) \s+ ($HOST_NAME) }xms; next if $HN ne $2; print "$1\n"; print "$2\n"; } __DATA__ 0.0.0.22 fred localhost 0.0.63.23 fred-test-0 1.0.128.24 fred-test-1