boobooboy has asked for the wisdom of the Perl Monks concerning the following question:

$hash = test::this(\%hash); for my $box (keys %{$hash}){ print "this is box $box\n"; for my $par (keys %{$hash{$box}}){ print "this is partition $par\n"; for my $sec (keys %{$hash->{$box}->{$par}}){ print "this is section $sec\n"; } } }
this is in package
sub this { $temp = @_; $Dbox = "Dbox"; $DDD = "DDD"; $temp{"Dbox"}= "Dbox"; $temp{Dbox}{$DDD}= "DDD"; for my $box (keys %temp){ print "this is box $box\n"; for my $par (keys %{$temp{$box}}){ print "this is partition $par\n"; for my $sec (keys %{$temp{$box}->{$par}}){ print "this is section $sec\n"; } } } return \%temp; }
-----------------------
this is box Dbox
this is partition DDD
-----------------------
start of main prog
this is box Dbox

the bottom lines are the outputs, as can be seen while
in the funtion it prints whaever I stored but when it
gets back to main, it only prints the Dbox (I dont
even know how)
am I doing somthing wrong here? (duh...that's why it doesn work) thankx guys...

Edited by Chady -- added code tags.

Replies are listed 'Best First'.
Re: Passing hash to package sub and get it returned ..
by kvale (Monsignor) on Apr 02, 2004 at 04:37 UTC
    It is hard to read your code (please add code tags), but it looks like in your this sub, you have
    $temp = @_;
    Evaluating @_ in scalar context just gives the number of elements, so $temp == 1. You want
    my $temp = shift; # or my ($temp) = @_;
    Once you process your hash using the $temp hashref, just return the ref:
    return $temp;

    -Mark

      Once you process your hash using the $temp hashref
      and it might be good to add that elements of the hash pointed to by $temp can be accessed like this:
      $temp->{"Dbox"} = "dbox"; # ^^^^

      -- Hofmator

Re: Passing hash to package sub and get it returned ..
by Taulmarill (Deacon) on Apr 02, 2004 at 08:21 UTC
    did you recognize that there are two variables called temp in your sub?
    $temp is used nowere, instead you use only %temp.
    i changed your code a bit, so it looks like this
    use strict; use warnings; my $hash = test::this(); for my $box (keys %{$hash}){ print "this is box $box\n"; for my $par (keys %{$$hash{$box}}){ print "this is partition $par\n"; # for my $sec (keys %{$hash->{$box}->{$par}}){ # print "this is section $sec\n"; # } } } package test; sub this { my $Dbox = "Dbox"; my $DDD = "DDD"; my %temp; $temp{"Dbox"}{$DDD}= "DDD"; for my $box (keys %temp){ print "this is box $box\n"; for my $par (keys %{$temp{$box}}){ print "this is partition $par\n"; # for my $sec (keys %{$temp{$box}->{$par}}){ # print "this is section $sec\n"; # } } } return \%temp; }

    use always use strict; use warnings; when you are messing around with things you dont fully understand.
    read perlreftut and perldsc->HoH.