On Aug 29, 9:41 am, [EMAIL PROTECTED] (Paul Lalli) wrote:
> On Aug 28, 11:16 pm, [EMAIL PROTECTED] (Phil) wrote:
>
>
>
> > Ok so here's the deal...I have the following:
>
> > $var = 123;
>
> > GetOptions( 'v|var=n'  => \$var);
>
> > %xyz = (
> >                 type1 => {  ABC => "after zero comes $var", },
> >                 type2 => {...etc.},
> >              );
>
> > get_var() if $condition;
>
> > sub get_var {
> >        $var = `external gui app to get input from user`;
> >        chomp($var);
>
> > }
>
> > print "$xyz{type1}{ABC}\n";
>
> > All looks good and well, but $var in %xyz retains it's original value
> > while the global variable $var gets changed to lets say 456, which is
> > a moot point since we're not printing $var, we're printing the hash
> > value..  I've tried declaring the subroutine before the hash, but it's
> > not really feasible considering the application, nor did it change the
> > outcome when I tried.  Using the command line option --var=456
> > obviously changes the variable before %xyz is even interpreted. So my
> > question is (as the title states)...how do I modify a variable in a
> > global hash value after the hash has been declared?  Keep in mind that
> > the key ABC => "etc.." must remain there since $condition won't always
> > exist, and since the option to modify it with --var also won't exist
> > when $condition is met.
>
> The problem is that the *variable* is NOT stored in that hash.  Only
> its value at the time of the initialization is stored.  When you
> interpolate a variable into a double quoted string, Perl simply takes
> the current value of that variable and puts it into the string.  There
> is no link of any kind between the string and the original variable
> from whence the value came.
>
> Here's one possible solution: store a reference to a subroutine that
> returns a certain string, rather than the string itself:
>
> %xyz = (
>                 type1 => {  ABC => sub { "after zero comes $var", },
>                 type2 => {...etc.},
>              );
>
> And then when you want to print the value, call the subroutine:
>
> print $xyz{type1}{ABC}->(), "\n";
>
> Here's a short-but-complete script that demonstrates this solution:
>
> #!/usr/bin/perl
> use strict;
> use warnings;
>
> my $var = '123';
> my %xyz = (
>              type1 => { ABC => sub { "value: $var" } }
>           );
>
> print "Before mod: ", $xyz{type1}{ABC}->(), "\n";
> $var = '456';
> print "After mod: ", $xyz{type1}{ABC}->(), "\n";
> __END__
>
> Output:
> Before mod: value: 123
> After mod: value: 456
>
> Hope this helps,
> Paul Lalli

That's exactly what I need to know.  Thanks a lot.


-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/


Reply via email to