in reply to RE: Making a Hash of Arrays
in thread Making a Hash of Arrays

Depends on your desired result. The first line would allow you to manipulate @array by manipulating the array referenced by $hash{$arg}, thus $hash{$arg}->[0] = 0 changes $array[0]. The second method builds a reference using the values in @array. Thus, modifying the array referenced by $hash{$arg} modifies something totally independent of @array. Either way is perfectly legal/valid, but it depends on what you're wanting to actually do.

Replies are listed 'Best First'.
RE: RE: RE: Making a Hash of Arrays
by japhy (Canon) on Sep 23, 2000 at 00:02 UTC
    That point is moot, since the array is lexically scoped (created via my()). So a reference to it would keep it around after it goes out of scope, so modifying it doesn't really pose a problem.

    Incidentally, there's a bit of optimization to be made in the program:
    sub processfile { my ($file, $list) = @_; my $script = "/export/home/limo/Perl/exfields.pl -e"; my %hash; # no need for @list for my $arg (split /,/ => $list) { open(FILE, "$script $arg $file |") or die "System error: $!\n"; while (<FILE>) { # did you mean /^(#|none|unkno)/ ? next if /^#|none|unkno/i; chomp; $hash{$arg} = [split]; # or, if there'll be another $arg of the same value.. # push @{ $hash{$arg} }, split; } close FILE; } # consider return a REFERENCE to the hash... # it might be more memory-effective return %hash; }
    If more description is needed than the comments provide, let me know.

    $_="goto+F.print+chop;\n=yhpaj";F1:eval
      I figured he was asking in the general-case, so that's what my post was geared towards.
      except, when I try and print the returned hash:
      my %first_hash = processfile($file2, $list2); foreach my $k (sort keys %first_hash){ print "$k\n$first_hash{$k}\n"; }
      it returns:
      MonName ARRAY(0xcb420) SrcRtr ARRAY(0xcb468) ifSpeed ARRAY(0xcb444)
      rather than the value of the keys.
        That's because they're REFERENCES to arrays. You need to dereference them (@{ $array_ref }).

        $_="goto+F.print+chop;\n=yhpaj";F1:eval
        So you need to dereference the arrays. @$arrayref.

        If you just need to know what's in the hash, use Data::Dumper. It does a great job of expanding references and can be made to do all sorts of pretty printing.

        use Data::Dumper; print Data::Dumper->Dump([\%yourhash], ["name of your hash"]), "\n";
        You can also use that to print your arrays and such.