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!


In reply to Re: Deleting certein elements from an array by haj
in thread Deleting certein elements from an array by Eso

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.