For Programmers: Free Programming Magazines  


Home > Archive > PERL Beginners > August 2005 > regex stored in variables ?









You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

 

Author regex stored in variables ?
Michael Gale

2005-08-23, 6:56 pm

Hello,

I have a script the loads regex into variables from a user config file,
how ever I am unable to get perl to run the regex against the string.

As I test have tried:

my $exp_test="m/^\d+$/";
if ( (defined $string) && ($string =~ $exp_test ) ) {
print $string, "\n";
}

I have tried many other variants but can't seem to get it to work.
Please help :)

Michael

Jeff 'japhy' Pinyan

2005-08-23, 6:56 pm

On Aug 23, Michael Gale said:

> I have a script the loads regex into variables from a user config file, how
> ever I am unable to get perl to run the regex against the string.
>
> As I test have tried:
>
> my $exp_test="m/^\d+$/";


That's got a couple problems with it, but I'm not going to get into them.

To store a regex (not a pattern match, mind you, but a regex) in a
variable, use the qr// constructor:

my $exp_test = qr/^\d+$/;

Then use it like so:

if ($string =~ $exp_test) { ... }

You can also embed that inside another regex:

if ($string =~ /$exp_test/m) { ... }

--
Jeff "japhy" Pinyan % How can we ever be the sold short or
RPI Acacia Brother #734 % the cheated, we who for every service
http://japhy.perlmonk.org/ % have long ago been overpaid?
http://www.perlmonks.org/ % -- Meister Eckhart
Michael Gale

2005-08-23, 6:56 pm

Ok,

I have tried your suggestion and it is working perfectly, but I want
to be able to load a variable from a file, so I am using the following
method to do so:

if ( -e "ConfigLoad.pm" ) {
use ConfigLoad;
$Config = new ConfigLoad();
} else {
&contact_func("ERROR: Could not find ConfigLoad.pm",1);
}

$Config->read($config_file) or die "Can't read config file $config_file";

Which has the following layout:

[section]
name=value

value will be my regex, so need to be able to do something like the
following (which I can not get to work)

my $exp_test=qr/$Config->get('section.name')/;

if ($string =~ $exp_test) { ....

I do not understand what I am missing / doing wrong ?

Thanks

Michael

Jeff 'japhy' Pinyan wrote:

> On Aug 23, Michael Gale said:
>
>
>
> That's got a couple problems with it, but I'm not going to get into them.
>
> To store a regex (not a pattern match, mind you, but a regex) in a
> variable, use the qr// constructor:
>
> my $exp_test = qr/^\d+$/;
>
> Then use it like so:
>
> if ($string =~ $exp_test) { ... }
>
> You can also embed that inside another regex:
>
> if ($string =~ /$exp_test/m) { ... }
>

Sponsored Links







Also available: Server administration forum archive | Web Design forum archive | Software forum archive | Hardware reviews archive

Copyright 2008 codecomments.com