On 9 May 2010 14:26, Harry Putnam <rea...@newsguy.com> wrote: > I have an example from Shawn C. from another thread, presented here > out of context. The code does just what he meant it to do. > It inverts a hash. > > I'm trying to understand what is going on inside the sub function > `invert()'. > > ------- --------- ---=--- --------- -------- > > my %hash = ( > './b/fb' => 'fb', > './b/c/fd' => 'fd', > './b/l/c/f2' => 'f2', > './b/g/f/r/fc' => 'fc', > './b/g/h/r/fb' => 'fb' > > ); > > ## %hash is sent to an inversion sub function > my %inv_hash = invert( \%hash ); > > sub invert { > my $h = shift @_; > my %inv = (); > > while( my ( $k, $v ) = each %{ $h } ){ > push @{ $inv{$v} }, $k; > } > return %inv; > } > > ------- --------- ---=--- --------- -------- > > What is actually being sent at > my %inverse_hash = invert( \%hash );
my %inverse_hash = invert( \%hash ); invert() is being passed a reference to the hash. References are a useful and efficient way to pass data around [1]. You can create a reference by putting a back-slash in front of your data. EG: my %foo_hash = ( foo => 1, bar => 2); # A hash my $reference_to_foo_hash = \%foo_hash; # Reference to the hash. > sub invert { > my $h = shift @_; References are scalars. So when you pass it to invert(), instead of passing in lots of keys and values, you pass in a single scalar reference to the hash. You shift off the single reference from the argument list. Any operation you perform on that reference will effect the original hash. In the interests of completeness I think I should also point out that you could have passed in the whole hash by not shifting off of the argument list. EG: my %inverse_hash = invert( %hash ); ... ... sub invert { my %original_hash = @_; But that's not a habit you want to get into as you are passing lots of values, passing by reference is saves memory and is faster. Good luck, Dp. 1) Apart from perdoc perlref, there is also the reference quick tutorial at http://perldoc.perl.org/perlreftut.html -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/