Loading ...
Sorry, an error occurred while loading the content.

Re: [PBML] remove elements of an array based on elements in another array

Expand Messages
  • merlyn@stonehenge.com
    ... Noah I want to remove elements from an array by comparing the elements for Noah the first array to the elements of a second array. Noah So in the
    Message 1 of 5 , Aug 27, 2012
    View Source
    • 0 Attachment
      >>>>> "Noah" == Noah <noah-list@...> writes:

      Noah> I want to remove elements from an array by comparing the elements for
      Noah> the first array to the elements of a second array.

      Noah> So in the example below if an element is in @ignore_routers that also
      Noah> appears in @devices then the element is removed from @devices.

      Noah> I thought this would work - but it does not.

      Noah> @devices = grep { !$seen{ $_ }++ } @ignore_routers, @devices;

      Noah> What is a better way to look at this?

      Build a hash from @ignore_routers, then look for membership in that hash
      for each element of @devices.

      --
      Randal L. Schwartz - Stonehenge Consulting Services, Inc. - +1 503 777 0095
      <merlyn@...> <URL:http://www.stonehenge.com/merlyn/>
      Smalltalk/Perl/Unix consulting, Technical writing, Comedy, etc. etc.
      See http://methodsandmessages.posterous.com/ for Smalltalk discussion
    • merlyn@stonehenge.com
      ... Alan use List::Util qw( first ); Alan @devices = grep { Alan my $device = $_; Alan !first { $device eq $_ } @ignore_routers;
      Message 2 of 5 , Aug 28, 2012
      View Source
      • 0 Attachment
        >>>>> "Alan" == Alan Haggai Alavi <alanhaggai@...> writes:

        Alan> use List::Util qw( first );

        Alan> @devices = grep {
        Alan> my $device = $_;
        Alan> !first { $device eq $_ } @ignore_routers;
        Alan> } @devices;

        Alan> Or, without using `first` from `List::Util`:

        Alan> @devices = grep {
        Alan> my ( $device, $select ) = ( $_, 1 );

        Alan> for my $ignore_router (@ignore_routers) {
        Alan> if ( $device eq $ignore_router ) {
        Alan> $select = 0;
        Alan> last;
        Alan> }
        Alan> }

        Alan> $select;
        Alan> } @devices;

        Those are both inefficient. Shlomi Fish (as usual) gave a far better
        answer.

        --
        Randal L. Schwartz - Stonehenge Consulting Services, Inc. - +1 503 777 0095
        <merlyn@...> <URL:http://www.stonehenge.com/merlyn/>
        Smalltalk/Perl/Unix consulting, Technical writing, Comedy, etc. etc.
        See http://methodsandmessages.posterous.com/ for Smalltalk discussion
      Your message has been successfully submitted and would be delivered to recipients shortly.