This is my first question on SO, so sorry if it’s silly, but it’s something that really puzzled me when I recently came across it in production code. I’ve boiled my problem down to the two blocks of code, which I expected to do the same thing, namely produce a random number for each iteration:
for my $num (0 .. 5) {
my $id = int rand 10;
print "$id\n";
}
and
for (0 .. 5) {
my $tmp;
my $id = $tmp if $tmp;
$id = int rand 10 unless $id;
print "$id\n";
}
The first one does what I expect it to do, but the second one gives the same number for any number of iterations. $tmp is always undefined in this simplification, so it’s only there to show the behaviour, as leaving out = $tmp if $tmp produces the result I’d expect.
I’d appreciate any insight into why this happens.
The reason for the strange behaviour is that you have made the declaration of
$id, as well as the assignment to it, conditional on the truth of$tmp, which makes Perl throw a fit.perldoc perlsynhas this to say about itYou can demonstrate this for yourself if you change the code as follows, which works fine.