The misunderstanding may be regarding what happens when you assign a hash ref to a glob rather than what local is doing.
#!/usr/bin/perl use strict; use warnings; use Data::Dumper; sub fillerup ($); my %fillme = (gas_pr => 3.59, gas_capacity => 14); local $\ = "\n"; print '-'x80; foreach my $key (keys %fillme ) { print $key . '=' . $fillme{$key}; } fillerup ( \%fillme ); print '-'x80; foreach my $key (keys %fillme ) { print $key . '=' . $fillme{$key}; } sub fillerup ($) { no strict; local *hashref = shift; # my $hashref = shift; print "Prior to inserting a record in fillerup..."; print '*'x80; foreach my $key (keys %$hashref ) { print $key . '=' . $hashref->{$key}; } $hashref->{filled_up} = 12.3; print '*'x80; foreach my $key (keys %$hashref ) { print $key . '=' . $hashref->{$key}; } print '*'x80; print "\*hashref: " . Dumper(*hashref); print "\$hashref: " . Dumper($hashref); print "\%\$hashref: " . Dumper(%$hashref); print "\\\%\$hashref: " . Dumper(\%$hashref); print "\\\%hashref: " . Dumper(\%hashref); print "\\\%fillme: " . Dumper(\%fillme); return; }
Produces
---------------------------------------------------------------------- +---------- gas_capacity=14 gas_pr=3.59 Prior to inserting a record in fillerup... ********************************************************************** +********** ********************************************************************** +********** filled_up=12.3 ********************************************************************** +********** *hashref: $VAR1 = *::hashref; $hashref: $VAR1 = { 'filled_up' => '12.3' }; %$hashref: $VAR1 = 'filled_up'; $VAR2 = '12.3'; \%$hashref: $VAR1 = { 'filled_up' => '12.3' }; \%hashref: $VAR1 = { 'gas_capacity' => 14, 'gas_pr' => '3.59' }; \%fillme: $VAR1 = { 'gas_capacity' => 14, 'gas_pr' => '3.59' }; ---------------------------------------------------------------------- +---------- gas_capacity=14 gas_pr=3.59
Update: See Typeglobs and Filehandles for more info on assignment to typeglobs. Note that assigning the reference to your global hash to your localized typeglob sets %hashref to be an alias to %fillme and does not set $hashref to a reference to the hash as you are expecting. You then autovivify $hashref with a reference to a new hash containing only the key 'filled_up', and leaving %hashref unchanged.
In reply to Re: Variable scoping and globs and reference passing to subroutines!!!
by ig
in thread Variable scoping and globs and reference passing to subroutines!!!
by MarkovChain
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |