Link to home
Start Free TrialLog in
Avatar of datastarstar
datastarstar

asked on

Why is my $1 variable empty after successful match in Perl?

This should be a no-brainer, but clearly I'm missing something obvious. Why doesn't this work? I'm just trying to get the contents of the matched portion of a string. It should be $1 right? Obviously, this is a very simple test -- my bigger application is much more complicated, so please tell me what I'm doing wrong.

Perl script:

my $var1 = "Hello";
print "original string: $var1";
if ($var1 =~ /Hello/ ) {print "<br>found";}
print "<br>matched string: $1";

Output:

original string: Hello
found
matched string:
SOLUTION
Avatar of FishMonger
FishMonger
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of datastarstar
datastarstar

ASKER

Duh, that worked! Hope you don't mind a follow-up question. What I'm really trying to do is to get the full contents of a file and load it into a hash using eval. This worked fine until I turned tainting on (-T switch). Since taint doesn't like eval unless using $1, I tried to regex match the entire contents like this. But even with the ()'s like you suggested $1 seems empty (print $1 yields nothing)...

my $filecontents=<INFILE>;  # the file contains a text representation of a hash definition
close FILE;
$filecontents =~ /(.*)/ )
print $1;
my %myHash = (eval($1));
Is the entire file just one line?
Ouch.  Given that small amount of info, it appears to me that you are using an awkward if not ugly approach to storing and retrieving your hash.  The Storable module or one of the config modules would be a better method.

Unless your file only has one line, you'll need to adjust how you're reading it into the scalar, which as written only reads in 1 line.
This line might be important for you to see:

undef $/;
my $filecontents=<INFILE>;
...

The file is actually very large -- hundreds of lines of hash defs.  If there's a better way to create a hash from a file, I'd love to hear it.

Thanks!
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thanks to you both. I'm using Ozo's fix initially but plan to adopt FishMonger's suggestion moving forward. Since FM answered the original question, I did a 2/3 - 1/3 split of the points. Hope that's fair.

Thanks again!