in reply to Passing variables into regular expressions


There's a couple of issues with your code that you should be aware of.

Firstly, when you slurp a file into a variable like that, the newline characters (\n) remain within the variable (i.e., you get exactly what was in the file).

To have your regular expression take that into account, you need to add a m alongside the g on the right-hand-side of the expression, which has Perl's regular expression engine match over multiple lines, rather than stopping when it hits the newline.

You can simplify the regular expression too to make your life a little easier. The following (working, but only partially tested) code snippet seems to do the job for me:

#! /usr/bin/perl use strict; use warnings; my $hn = 'localhost.localdomain'; my $hosts = `cat /etc/hosts`; if ( $hosts =~ /^([\d\.]+)\s+($hn)/mg ) { print "true: $1 $2\n"; } else { print "false!\n"; }
Having said that, there's almost certainly a better way to parse this file .. but I'm not caffienated enough to think of it at the minute.

Hope that helps!