Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

Re: The error says the value is uninitialized, but it works anyway

by karthiknix (Sexton)
on Aug 21, 2019 at 09:53 UTC ( #11104794=note: print w/replies, xml ) Need Help??


in reply to The error says the value is uninitialized, but it works anyway

The code uses splice to remove the elements from the array but the size of the array is not adjusted in the foreach loop. Below code would traverse the array based on the last index of the array. This works even after using warnings module without any error. Here I am adjusting the for loop count based on your splice.

use warnings; print "hello world\n"; my @colors = qw(red green blue yellow pink purple brown); my @drop = qw(pink brown); my $num = 0; for (0..$#colors){ if ($colors[$num] eq $drop[0] or $colors[$num] eq $drop[1]){ + splice (@colors, $num, 1); $num--; } $num++; } print "@colors \n";
  • Comment on Re: The error says the value is uninitialized, but it works anyway
  • Download Code

Replies are listed 'Best First'.
Re^2: The error says the value is uninitialized, but it works anyway
by soonix (Abbot) on Aug 21, 2019 at 13:02 UTC
    if ($colors[$num] eq $drop[0] or $colors[$num] eq $drop[1]){ + splice (@colors, $num, 1); $num--; } $num++;
    Just as a nitpick: I think it's better to
    if ($colors[$num] eq $drop[0] or $colors[$num] eq $drop[1]) { splice (@colors, $num, 1); } else { $num++; }
    because find it's somehow dopey (for lack of a better word) to decrement just to increment immediately afterwards.
    With "else" it's clear that you need to increment only if the condition isn't met.

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (3)
As of 2019-11-18 07:17 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Strict and warnings: which comes first?



    Results (88 votes). Check out past polls.

    Notices?