in reply to Slicing a hashref

I am not entirely sure what data you have since you are
mentioning DBI code as well. If you are merging two query
results would it be possible to merge the query rather then
the results?

Anyway as for merging two hashrefs, here is my code for that

$hash1 = { a => '56', b => '75', c => '87' }; $hash2 = { d => '45', f => '46', g => '67', }; my $hash3 = { %$hash1, %$hash2 }; foreach (keys %$hash3) { print "$_ = $hash3->{$_}\n"; }

Replies are listed 'Best First'.
Re: Re: Slicing a hashref
by trs80 (Priest) on Jan 20, 2002 at 05:40 UTC
    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?