in reply to Fast Way to Combine Two Hashes

I don't know if it is faster but at least it is shorter:

@set2{keys %set1}=undef;

You can test it with:

#!/usr/bin/perl -w use strict; my %set1=( k1 => 1, k2 => 2, k4 => 2); my %set2=( k1 => 1, k3 => 2, k4 => 2); @set2{keys %set1}=undef; while( my( $k, $v)= each %set2) { $v='undef' unless( defined $v); print "$k => $v\n"; }

Replies are listed 'Best First'.
Re: Re: Fast Way to Combine Two Hashes
by runrig (Abbot) on Jun 19, 2002 at 00:01 UTC
    or alternatively (and I suspect the fastest way):
    undef @hash2{keys %hash1};

      Actually not. If you look at the original question, all values for the keys of %set2 should be set to undef. undef @set2{keys %set1}; leaves the original value in the hash. @set2{keys %set1}=undef; performs exactly as the original foreach $key (keys %set1) { $set2{$key} = undef; }.

      In fact @set2{keys %set1}= (undef) x scalar keys %set1; is more correct (thanks to Zaxo for providing it), but might be slower.

        all values for the keys of %set2 should be set to undef

        They are undef, try this:

        my %hash2; undef @hash2{qw(a b c)}; my %hash1; undef @hash1{qw(c d e)}; undef @hash2{keys %hash1}; print "$_ ",defined($hash2{$_})?"def\n":"undef\n" for keys %hash2;
        This technique works great when you want undefined don't care about the values. If you want to preserve defined values, then you have to do something like what Zaxo has.

        Update: corrected by mirod, anyway, this works great when working with sets and you don't care about the values.