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

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
  • Comment on Re^2: Passing variables into regular expressions

Replies are listed 'Best First'.
Re^3: Passing variables into regular expressions
by GrandFather (Saint) on Apr 20, 2006 at 10:12 UTC

    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