Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Help using variables in a reg. exp... 1

Status
Not open for further replies.

jtb1492

Technical User
Mar 17, 2005
25
US
I want to do something like this...

%jason = (
red => ((//^one/ and /two/) or (/^three/ and /four/)),
green => ((//^five/ and /six) or (/^seven/ and /eight/))
);

foreach $key ( keys %jason ) {
if $jason{$key} {
do_stuff
}
}

but that doesn't work...how do I get this done?
I want the 'if $jason{key}' line to be like I wrote:
if ((//^one/ and /two/) or (/^three/ and /four/))

Hopefully there's an easy way to write what I mean...
 
You could make the hash values code references. This seems to do what you want.
Code:
#!perl
use strict;
use warnings;

my %jason = ( 
    red => [b]sub{/^one/ && /two/ || /^three/ && /four/}[/b],
    green => [b]sub{/^five/ && /six/ || /^seven/ && /eight/}[/b],
);

while (<DATA>) {
    my $found = 0;
    for my $key (keys %jason) {
        if ([b]&{$jason{$key}}[/b]) {
            $found++;
            print qq(line $. matches $key\n);
        } 
    }
    print qq(line $. no match\n) unless $found;
}

__DATA__
one two buckle my shoe
two plus two is four
three four shut the door
five six pick up sticks
Nothing here
seven eight wake up late
Output:
Code:
line 1 matches red
line 2 no match
line 3 matches red
line 4 matches green
line 5 no match
line 6 matches green
Might be a simpler way to do what you want, though. So I would echo audiopro's question: What are you trying to achieve?


 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top