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

Currently I am doing the following:
while( <$fd> ) { my $href = { map { split '=' } split ';' }; my $id = (split '\.', $href->{TOKEN})[1]; $tokens{$id} = { %{ $href } } }
Is there a better way to add $href to %tokens than dereferencing it and creating a new anonymous hash reference? Using Perl 5.8.0 on Solaris. Thanks!

-- Argel

Replies are listed 'Best First'.
Re: Better way to add refs to an array or hash?
by cog (Parson) on Mar 25, 2005 at 00:39 UTC
    I believe a simple

    $tokens{$id} = $href;

    should do the trick... (unless I'm missing something obvious, because I'm about to fall asleep)

      Cog: You're right. I had another bug that was corrupting $id that confused me. ( Hangs head in shame )
      -- Argel
Re: Better way to add refs to an array or hash?
by Tanktalus (Canon) on Mar 25, 2005 at 00:53 UTC

    There's always MTOWTDI ... You've just managed to find one of the more extreme methods (without going into function calls). As cog said, you can just assign $tokens{$id} = $href. But the other way (my preference) would be:

    while (<$fd>) { my %href = map { split '=', $_, 2 } split ';'; my $id = (split '\.', $href{TOKEN})[1]; $tokens{$id} = \%href; }
    Of course, there are a bazillion ways to get the text between the first and second dot, but that's not the question here, so I'm leaving well enough alone. The only real change to that line was the removal of the arrow notation since I changed from using a hashref to using just a plain hash. Each time through the loop, we'll get a new hash, and the %tokens hash will have references to no-longer-named hashes that have otherwise fallen out of scope. Either solution (cog's or this one) should be faster than yours (no copying), but otherwise there's probably no significant difference between them (likely the same speed). The only difference is the sigils.

      Thanks for the suggestion Tanktalus! I switched over to using it instead (renamed href to hash to be clearer).
      -- Argel
Re: Better way to add refs to an array or hash?
by Mugatu (Monk) on Mar 25, 2005 at 00:51 UTC
    The answer cog provided is correct. The general rule is that array and hash values can only be scalars. You have a hash reference, which is already a scalar. Thus, you can insert it directly in as the hash value.
Re: Better way to add refs to an array or hash?
by gam3 (Curate) on Mar 25, 2005 at 00:54 UTC
    Since $href contains the only reference to the hash you should be able to use it directly.
    -- gam3
    A picture is worth a thousand words, but takes 200K.