http://qs321.pair.com?node_id=1229536


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.