Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number

Re: Deleting certein elements from an array

by haj (Priest)
on Feb 07, 2019 at 12:14 UTC ( #1229536=note: print w/replies, xml ) Need Help??

in reply to Deleting certein elements from an array

This is a problem where it really, really pays off to familiarize with some Perl idioms. The other comments showed steps to get to a result beginning with the code - here's another approach beginning with your problem.

Whenever I see a for loop containing a push, the map function springs into my mind. Together with grep to remove unwanted elements from a list, the code collapses to a few lines (Note that I also dropped use feature qw/say/; because that comes automatically with use 5.10.1;):

#!/usr/bin/perl use strict; use warnings; use 5.10.1; my $all_the_numbers=int(rand(19)); my @rand = map { 20-int(rand(30)) } (1..$all_the_numbers); say "@rand"; @rand = grep { $_ < 0 } @rand; say "@rand";

The function map takes a list to the right (note how I wrote that list without a loop), and applies the code block to each of the elements, to create a new list. In our case, we just create a new random number per element.

The grep function checks a code block against each element of a list and returns a new list containing only those elements where the code block evaluates to a true value. $_ is Perl's magical variable which holds the current value of the list while walking through it (To be precise, it is an alias to the list element, but this doesn't matter in our case).

Edit: Fixed the grep condition as detected by hdb in Re^2: Deleting certein elements from an array. Thanks for spotting this!

Replies are listed 'Best First'.
Re^2: Deleting certein elements from an array
by hdb (Monsignor) on Feb 07, 2019 at 13:03 UTC

    Good explanation! However, the original question was to keep the negative elements of the array and thus it should be

    @rand = grep { $_ < 0 } @rand;
      Drats... I fixed it in my test file but forgot to paste back. Thanks! I'll fix it.

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1229536]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others examining the Monastery: (3)
As of 2022-06-26 13:51 GMT
Find Nodes?
    Voting Booth?
    My most frequent journeys are powered by:

    Results (85 votes). Check out past polls.