Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Variable scope headaches

by nikmit (Initiate)
on Jul 26, 2012 at 15:36 UTC ( #983857=perlquestion: print w/ replies, xml ) Need Help??
nikmit has asked for the wisdom of the Perl Monks concerning the following question:

Hey guys,

I am attempting to assign values to variables like this:

foreach (@tagvalue) { if ($_ =~ /([\w,_]+):([0-9]+)/) { ${$1} = $2; } else { die "Failed to assign value to $1\n"; } }
The result is that within the foreach loop all is good, but outside of it the variables are empty... I tried to use
our ${$1} = $2;
but get an error on execution: 'Can't declare scalar dereference in "our"'.

./headbang

Comment on Variable scope headaches
Select or Download Code
Re: Variable scope headaches
by jdporter (Canon) on Jul 26, 2012 at 16:29 UTC

    Trying to use a variable as a variable name (i.e. "symbolic references") is generally considered a bad idea.

    There is an item in the perlfaq about this: How can I use a variable as a variable name?. I highly suggest you read this.

    It is considered critical enough that it is explicitly detected and forbidden by use strict; - the inclusion of which is universally considered good practice.

    Instead, use a hash variable:

    my %tag_value; foreach ( @tagvalue ) { if ( /([\w,_]+):([0-9]+)/ ) { $tag_value{$1} = $2; } else { die "Failed to assign value to $1\n"; } }

    By the way I think your die statement is going to have a problem, in that $1 will not be set (at least not to what you think) if it ever gets executed. If the pattern match (regex) fails to match, then none of the positional variables ($1, etc.) get set. Instead, you might say something like:

    die "Failed to match tag/value in '$_'\n";
    I reckon we are the only monastery ever to have a dungeon stuffed with 16,000 zombies.
      Thanks jdporter

      I actually had read that perlfaq item, obviously it didn't quite sink in :) Works now, and code looks better.

      Thanks for pointing out the 'die' statement error too. I have removed that block of code now but clearly its one to watch out for.

      nik

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://983857]
Front-paged by Corion
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others surveying the Monastery: (8)
As of 2014-12-25 08:01 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (159 votes), past polls