in reply to Remove redundency from an array

This is, as has shown here, a fairly
often used and well documented task.

Sometimes I'd use snippet that reads like
my @array = (1,1,3,3,2,3,5,7,5,2); # uniqify without modules @array = do { @$_{@array} = (); keys %$_ };

Regards

M.

Replies are listed 'Best First'.
Re^2: Remove redundency from an array
by jdporter (Paladin) on Sep 24, 2007 at 18:56 UTC

    Of course, that clobbers $_. Perhaps you want to insert

    local *_;
    at the beginning of that do block.

      jdporter: Of course, that clobbers $_. Perhaps you want to insert local *_; ...

      Would this (*_) be relevant here?

      $_ *might* be localized, but *_ imho not.

      consider:
      sub uinq { # local *_; # <== will fail, $_ will work @_ = do { @$_{@_}=(); keys %$_ }; @_ } my @array = (1,1,3,3,2,3,5,7,5,2); print "@{[ uinq @array ]}\n";


      Regards & thanks
      mwa

        First, local *_ does work if you put it in the do block like jdporter said.

        Secondly, local $_ won't work. It'll compile, but that doesn't count for anything if it doesn't do what needs to be done. We want to protect the parent's %_.

        Good point. It's up to you (the programmer) to protect/preserve the contents of @_ if necessary. It wasn't necessary in the code you gave.

        ikegami may be too modest to point out his previous discursion on the subject.

Re^2: Remove redundency from an array
by Roy Johnson (Monsignor) on Sep 24, 2007 at 21:48 UTC
    Better to use either a lexical hash in the do-block, or an anonymous hash:
    @array = keys %{ {map {$_,undef} @array} };

    Caution: Contents may have been coded under pressure.