in reply to Passing variables into regular expressions

Your code doesn't make a great deal of sense to me. In particular I can't see why you are interpolating $HN into the regex. However the following sample does what you ask and should serve as a starting point for you to ask what you really want to know:

use strict; use warnings; while (<DATA>) { next if ! /^((?:\d{1,3}\.){3}\d{1,3})\s+(\S*)/; 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 0.0.63.23 fred-test-0 1.0.128.24 fred-test-1

Note the use of \d{1,3} to match 1 to 3 digits and \s and \S to match white space and anything else respectively.


DWIM is Perl's answer to Gödel

Replies are listed 'Best First'.
Re^2: Passing variables into regular expressions
by Anonymous Monk on Apr 20, 2006 at 10:06 UTC
    Thanks for your quick response. Just to clarify the requirement I only want to get the IP address on the line containing 'fred' not 'fred-test..' In addition this script will be run on over 300 servers so that is why I am passing the $HN into the regexp

      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
        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