Solved

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

Posted on 2014-11-13
8
207 Views
Last Modified: 2014-11-14
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:
0
Comment
Question by:datastarstar
  • 3
  • 3
  • 2
8 Comments
 
LVL 28

Assisted Solution

by:FishMonger
FishMonger earned 334 total points
ID: 40440959
You forgot to capture the match i.e., you forgot the parens.

if ($var1 =~ /(Hello)/ ) {print "<br>found";}

Open in new window

0
 

Author Comment

by:datastarstar
ID: 40441156
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));
0
 
LVL 84

Expert Comment

by:ozo
ID: 40441172
Is the entire file just one line?
0
 
LVL 28

Expert Comment

by:FishMonger
ID: 40441303
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.
0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 

Author Comment

by:datastarstar
ID: 40441570
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!
0
 
LVL 84

Assisted Solution

by:ozo
ozo earned 166 total points
ID: 40441688
Maybe
do "filename";
or
$filecontents =~ /(.*)/s
0
 
LVL 28

Accepted Solution

by:
FishMonger earned 334 total points
ID: 40441727
I would need to see a sample of your file to see if we can parse it directly with one of the config modules without altering how it gets created.

Here's an example how you can use the Storable module to store the hash in a file for later retrieval either in the same script or some other script.

#!/usr/bin/perl

use strict;
use warnings;
use Storable qw(store retrieve freeze thaw dclone);

my %orig_hash = (
    foo => 'foo',
    bar => 'bar',
    baz => 'baz'
);

store(\%orig_hash, 'hash.cfg');


# you can retrieve the hash data as a regular hash or as a hash_ref
my %retrieved_hash = %{ retrieve('hash.cfg') };

foreach my $key (keys %retrieved_hash) {
    print "$retrieved_hash{$key}\n";
}

Open in new window


If the file defines multiple hashes, then the Storable module may not best solution.  In that case, I'd go with one of the other config modules.

If the file is setup correctly, then the do "filename" as ozo suggests would be the shortest/easiest solution, but is not the approach I would personally use in a production script.
0
 

Author Comment

by:datastarstar
ID: 40443000
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!
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

I have been pestered over the years to produce and distribute regular data extracts, and often the request have explicitly requested the data be emailed as an Excel attachement; specifically Excel, as it appears: CSV files confuse (no Red or Green h…
A year or so back I was asked to have a play with MongoDB; within half an hour I had downloaded (http://www.mongodb.org/downloads),  installed and started the daemon, and had a console window open. After an hour or two of playing at the command …
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
Both in life and business – not all partnerships are created equal. As the demand for cloud services increases, so do the number of self-proclaimed cloud partners. Asking the right questions up front in the partnership, will enable both parties …

911 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now