Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

Re: Deleting certein elements from an array

by Eily (Monsignor)
on Feb 07, 2019 at 09:22 UTC ( [id://1229525]=note: print w/replies, xml ) Need Help??


in reply to Deleting certein elements from an array

Hello Eso. The first thing I notice in your code is that you loop with the condition $all_the_numbers<20, but $all_the_numbers never changes, meaning you have to exit the loop manually with last (last should mostly be used for early exit, not for the normal stopping condition). The more perlish way to loop a given number of times is:

for (0..$all_the_numbers) { ... # This will be called $all_the_numbers+1 times # (eg, if $all_the_numbers is 1, it will be called for 0 and 1, +so twice) }

About what you are trying to do: it's simpler to avoid modifying an array while you are iterating over it (looping on it's elements). So you should build the second list in a separate array, which you can either do at the same time as the first one, or in a separate loop, like this:

for (0..$all_the_numbers) { my $number = 30 - int(rand(20)); push @all_rand, $number; # Always add to all_rand; next if $number >= 0; # Skip if number is positive push @negative_only; }
Or first build @all_rand, then in a separate loop:
for my $random_number (@all_rand) { push @negative_only if $random_number < 0; }
You still have to declare the variables, and correct the +1 offset on $all_the_numbers.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others imbibing at the Monastery: (6)
As of 2024-04-23 20:36 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found