Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

Re: Relative Merits of References

by clinton (Priest)
on May 11, 2006 at 14:19 UTC ( [id://548717]=note: print w/replies, xml ) Need Help??


in reply to Relative Merits of References

Why do you think that that construct is illegal? I tried this code in perl 5.8.7 and it works without any warnings.

use strict; use warnings; use Data::Dumper; my $a; %$a=(a=>1,b=>2); print Dumper($a);

And it prints

$VAR1 = { 'a' => 1, 'b' => 2 };

UPDATE : I see now that the illegal part was the "my %$h" part rather than the assigment part. So that could have been changed simply by splitting the declaration to a separate line, or by changing the list to a {}.

However it seems an odd way to do it when you could just say :

$a={a=>1,b=>2};

I benchmarked the two versions, and the first %$a=() is 50% slower than the second ($a={}).

Regarding the difference between $h{name} versus $h->{name}, there is a slight speed difference (10%), because the second version first needs to dereference $h before doing the lookup, but it is so blazingly fast that I wouldn't worry about it. (Tested on a small hash - not sure for bigger hashes)

Rather just use whatever is easier to read, as there are bound to be other bottlenecks that make much more difference to your code's performance.

Replies are listed 'Best First'.
Re^2: Relative Merits of References
by ikegami (Patriarch) on May 11, 2006 at 14:25 UTC
    You can't change the code, show that the changed code is legal and claim the original was legal.

    The OP has
    my %$a=(a=>1,b=>2);
    You have
    my %a; %$a=(a=>1,b=>2);

      Yep, I missed the significance of the my %$h = .... I'm thinking back now to dimly remembered exam advice from more than thirty years ago, "Read the question carefully before answering." I'll try to pause for thought next time.

      Cheers,

      JohnGG

Re^2: Relative Merits of References
by UnderMine (Friar) on May 12, 2006 at 13:19 UTC

    %$a={a=>1, b=>2};

    I would need to check but it looks like it does the assignment of the hash in $a and then copies it into a hash (%) which is then thrown away as it is unassigned.

    I don't have a copy of 5.6 available but it would be interesting to see if my %$a assigned both %a and $a via the glob. In 5.8 it appears to do as suggested earlier.

    UnderMine

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://548717]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others perusing the Monastery: (4)
As of 2024-04-19 02:56 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found