Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

Deleting Elements from an Array without their Index Number?

by Spidy (Chaplain)
on Jul 23, 2006 at 21:17 UTC ( [id://563155]=perlquestion: print w/replies, xml ) Need Help??

Spidy has asked for the wisdom of the Perl Monks concerning the following question:

I solved the problem before this node was approved, please reap.

Janitor note: Original content follows:

Greetings Fellow Monks,

I have an array, that is filled with a number of elements. For example:

my @array = qw(penny coin dutch);

And I want to delete the 'coin' entry, while only having the 'coin' value(not the index number of that element within the array). Does anyone know how exactly I'd do this?


Thanks,
Spidy

Considered by GrandFather: Restore original content and title
Content restored by Arunbear, using the mirror of g0n.

Replies are listed 'Best First'.
Re: Deleting Elements from an Array without their Index Number?
by Corion (Patriarch) on Jul 23, 2006 at 21:19 UTC

    Do you want to remove coin from the array?

    my @not_coin = grep { $_ ne 'coin' } @array;

    Or do you want to replace coin by undef?

    my @not_coin = map { $_ eq 'coin' ? undef : $_ } @array;

      And of course you could also use grep to determine the index if you later would like to use it to remove elements with splice.

      my @coin_idx = grep { $array[ $_ ] eq 'coin' } 0..$#array;

      I like how writing these as map+ternary makes it obvious that grep is just a specialization of map.

      my @not_coin = map { $_ eq 'coin' ? () : $_} @array; # Or do you want to replace coin by undef? my @not_coin = map { $_ eq 'coin' ? undef : $_} @array;

      ⠤⠤ ⠙⠊⠕⠞⠁⠇⠑⠧⠊

        And map is a specialization of foreach+push.
        my @not_coin; foreach (@array) { push(@array, $_ eq 'coin' ? () : $_); }
        How does this help?

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://563155]
Approved by Arunbear
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others perusing the Monastery: (4)
As of 2024-04-20 02:01 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found