Hi there, newbie here. I'm trying to compile a program which has to generate an array containing random numbers (including negative ones), but no more than 19. After that, every positive number in the above-mentioned array has to be deleted, making it contain only the negative ones. The whole code looks like this:
#!/usr/bin/perl
use strict;
use warnings;
use feature qw/say/;
use 5.10.1;
my @rand=();
my $all_the_numbers=int(rand(19));
my $i=0;
while ($all_the_numbers<20)
{
my $number=20-int(rand(30));
push @rand, $number;
$i++;
last if $i==$all_the_numbers;
}
say "@rand";
my $h=0;
while ($all_the_numbers<20)
{
for (@rand)
{
if ($rand[0]<0)
{
next; #in order to make it skip the negative ones
}
shift @rand;
}
$h++;
last if $h==$all_the_numbers;
}
say "@rand";
However, this resoults in deleting only the positive numbers that come before the first negative one in the array, leaving what comes right after it untouched... So, how is it that the while loop doesn't keep on deleting the positives? Here's a picture to better explain myself: https://i.ibb.co/Gkmj8jc/Immagine.png
Thanks in advance.
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|