This was bugging me for AGES ! So I thought I would register and give something back to the Monks.... This snippet does four things:

Passes a Hash by reference (function b)

Adds some key/value pairs to the hash

Prints the hash using a recursive function (so the hash can be in any form, i think)

Passes (in effect) the hashes within the main hash to the recursive function.

It's taken me a while to work out references in perl. I hope it is useful to someone.

#!/opt/bin/perl5 my %c; b(\%c); #print as normal if(0) { for $i (keys %c) { print "$i = $c{$i}\n"; for $a (keys %{$c{$i}}) { print "$i = $c{$i} = $c{$i}{$a}\n"; } } } sub b { my($c)=@_; $$c{b} = 'b'; $$c{c} = 'c'; $$c{b}{a} = 'ba'; $$c{b}{v} = 'bv'; $$c{b}{v}{g} = 'bvg'; print "printing c{b}{v} = $$c{b}{v}\n"; recref($c,""); } #pass this function a reference to a hash sub recref { my($cref,$str)=@_; my $i; my $prefix; for $i (keys %{$cref}) { $prefix = $str . "." . $i; print "$prefix = $$cref{$i}\n"; recref($cref->{$i},$prefix); } }

Replies are listed 'Best First'.
Re: Passing Hashes by Reference
by belg4mit (Prior) on Jan 10, 2002 at 00:06 UTC
    Heh heh heh heh, Where's Perl?

    Anyways, what's the purpose of this really? Did you ever read perlref or perlreftut?

  • The 3rd thing the snippet done is done by Data::Dumper
  • You could simply reassign $str there is no need for $prefix; $str .= "." . $i;
  • --
    perl -pe "s/\b;([st])/'\1/mg"

      hah, I don't administer the machines...

      In reply...

      Yes I have read the documents, but found them a little confusing. I'm sure I'm not the only one... examples always help.

      I am familiar with Data::Dumper, but, the function is pretty small, and does not require Data::Dumper to be installed on the machines which I do not administer. ;)

      string re-assignment, yep, I should have done that :)