I started wondering how effcient my solution might be since Perl is not as efficient with hashes as it is arrays. So I compared it to what tilly posted.

@$old{keys %$new} = values %$new;
I did a benchmark on each block of code.

Benchmark: timing 1000000 iterations of tilly_way, trs80_way...
 tilly_way: 11 wallclock secs 
    (10.27 usr +  0.00 sys = 10.27 CPU) @ 97408.92/s (n=1000000)
 trs80_way: 26 wallclock secs 
    (24.16 usr +  0.00 sys = 24.16 CPU) @ 41382.16/s (n=1000000)

So don't do it the trs80_way for two reasons. One it is hard for someone new to Perl to know what is going on in the trs80_way. Second it is slower, although it won't make a hill of beans difference if you only work with small hashes.

That said, I still think the trs80_way looks cooler :^)


Reference data:
Benchmark script:
use Benchmark; $hash1 = { a => '56', b => '75', c => '87' }; $hash2 = { d => '45', f => '46', g => '67', }; timethese(1000000, { trs80_way => sub { $hash1 = { %$hash1, %$hash2 }; }, tilly_way => sub { @$hash1{keys %$hash2} = values %$hash2; + }, } );

Benchmark module documentation (this is a little out of date)

I vaguly remember this in either TPJ or the Perl Cookbook, anyone else remember?

In reply to Re: Re: Slicing a hashref by trs80
in thread Slicing a hashref by George_Sherston

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.