in reply to Re: Adding Unique Elements to Array
in thread Adding Unique Elements to Array

While both of these work, neither is very good code. In the first example, you pass undef an array slice, but undef doesn't work on array slices (you're just not using undef for its designed purpose, so you don't care). It would be better to say
@hash{@list} = ();
In the second, you use grep where a foreach is more sensible. In fact,
1 for @hash{@list};
works just as well (you don't even have to assign anything).

Caution: Contents may have been coded under pressure.

Replies are listed 'Best First'.
Re^3: Adding Unique Elements to Array
by RazorbladeBidet (Friar) on Feb 28, 2005 at 20:44 UTC
      I'm not sure whether you're making your case based on cargo cultism or micro-optimization; neither is a good idea. Abusing undef benchmarks at about 20% faster than assigning empty list, but it relies on undocumented behavior.

      You can get within 2% by saying

      @hash{@list} x= 0;
      which is still odd (and gives a warning for using uninitialized values), but is at least documented, if your code is bottlenecking at your key-creation section. In the absence of a bottleneck, it is better to write clear code than marginally faster code.

      Caution: Contents may have been coded under pressure.

        The fact is that your x= tricks works as just as much as the undef() because of undocumented behaviour. This is shown by

        my $foo; sub context :lvalue { $foo = wantarray ? 'list' : 'scalar' } context() x= 1; print $foo; __END__ scalar
        or using simpler means:
        use Data::Dumper; my %foo = qw/ a 1 b 2 /; @foo{qw/ a b /} x= 0; print Dumper \%foo; __END__ $VAR1 = { 'a' => '1', 'b' => '' };
        A trick that does work though is the reference trick. All these other solutions work because of autovivification. So let's use \ whose behaviour explicitly is documented.
        \@foo{@list};

        ihb

        See perltoc if you don't know which perldoc to read!

        My only argument was to show some sort of precedence, benchmark results and optional ways of doing things. Of course there are going to be sub-optimal ways of doing things, balancing out clarity and performance. I think it is inappropriate to charge either of those with "cargo cultism" or "micro-optimization".

        The two ways presented were simply options at the disposal of the user. I agree undocumented or obfuscated code should be used with care or not at all, however I also know plenty of people that tend away from "use strict". To each their own.
        --------------
        It's sad that a family can be torn apart by such a such a simple thing as a pack of wild dogs