in reply to need explanation of @foo{@bar} = (); (hash slice)
An alternative usage for what you posted, having the same end-result is
@saw{@in} = undef;
Because of autovivification-related bugs, I got into the habit of using defined instead of exists to determine whether a hash contains a certain key. This habit required developing the second habit of using something like
instead of@saw{@in} = (1) x @in;
As I say, these are just programming habits; with a modicum of vigilance it is perfectly possible to avoid autovivification bugs and still use the @saw{@in} = () idiom. In fact, vigilance would be cheaper than my habit, which costs me a 10% premium in the size of the resulting hashes:@saw{@in} = ();
I'm willing to pay this price to avoid heart-stopping encounters with lines like this in my codeDB<1> use Devel::Size 'total_size' DB<2> @x{1..1000}=() DB<3> @y{1..1000}=(1) x 1000 DB<4> p total_size(\%x) 41049 DB<5> p total_size(\%y) 45049
and the resulting frantic code scan to ensure that it doesn't contain anything likeif ( exists $some_hash{ foo } ) { launch_the_missiles(); }
$x = $some_hash{ maybe_foo() }{ bar };
Now I use exists only when dealing with the rare hash for which undef is a legitimate value.
Update: A related idiom, which, in addition to removing duplicates, also preserves the original order as much as possible, is:
my @no_repeats = do { my %h; grep !$h{$_}++, @has_repeats };
the lowliest monk
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: need explanation of @foo{@bar} = (); (hash slice)
by davido (Cardinal) on May 08, 2005 at 16:49 UTC | |
by tlm (Prior) on May 08, 2005 at 17:17 UTC | |
by davido (Cardinal) on May 09, 2005 at 01:52 UTC | |
by tlm (Prior) on May 09, 2005 at 02:24 UTC |