Home: Perl Programming Help: Regular Expressions:
variables in regular expressions


Jul 6, 2001, 10:05 AM

Views: 16771
variables in regular expressions

I am trying to use 2 variables in my regex and I can't get it to work. I can never get it to evaluate to true. Here's a code snippet ------>


%hash = (data => "");

$entry = "";

if ($entry =~ m/%hash->{'data'}+/) {

print "Match\!\n";


Can someone please tell me what I'm doing wrong?

thanks for your help


Jul 6, 2001, 10:45 AM

Views: 16767
Re: variables in regular expressions



if ($entry =~ m/%hash->{'data'}+/) {


if ($entry =~ m/$hash{'data'}+/) {

I Hope this helps...

perl programmers don't die.. they just start writing a new script.


Jul 6, 2001, 12:15 PM

Views: 16765
Re: variables in regular expressions

I tried that and now I get a match every time,,,whethere the hash is included in my script or not. I am running a program called mrtg to monitor our routers which outputs some html files for each router into a predefined directory. I want to do a couple of things with the html files. The html files are named the same - is a good example. I want to parse the ip address out of the filename and compare it to a record in a table in the mysql database. If it's found in the database, I want to query and see if the ip( and interface(se0.1) exist in the interfaces table. So basically I need to setup the query, execute it, read the path where the file should be, if it's there parse the filename and put the ip/interface into the interfaces table. That shouldn't be too hard with perl, right? :-)

thanks for all of your help


Jul 6, 2001, 12:58 PM

Views: 16764
Re: variables in regular expressions


I've commented the code, so it shouldn't be hard to understand.

#!/usr/bin/perl -w 
use strict;
use warnings;

# Use the following to see what the
# regex engine is actually doing...
use re 'debug';

my $entry = "";

my %hash = (data => "");

# All strings that are about to be
# interpolated into a regex should
# be quotemeta'd before. Otherwise,
# the dots will match any character!
$_ = quotemeta foreach values %hash;

# Now, we want to check if $entry
# begins with $hash{data}...
if( $entry =~ /^$hash{data}/ ) {
print "Match!\n";

If you have any specific questions, feel free to ask. Hope this helps.

-- Marcus