I’m reading the Llama (Learning Perl) book, and working on the exercises. And for this exercise:
Write a program that reads a list of strings on separate lines until end-of-input and prints out the list in reverse order. [. . .]
Well, I already figured out a simpler approach (I remembered you could use reverse on arrays… Perl is so… awesome so far), but I am wondering why this one isn’t working.
#!/usr/bin/perl
use 5.010;
chomp(@strings = <STDIN>);
foreach (@strings){
push @revstrings, $_;
}
while($i++ <= scalar @revstrings){
say pop @revstrings;
}
It goes like this:
$ ./first
one
two
three
[^D]
three
two
$
the output is the same if I change the <= in the while loop to just <.
You’ll never get past halfway… Each time through that last iteration, you’d get:
$i++means that$iwill increase by one;pop @revstringswill mean thatscalar @revstringswill decrease by one.They’ll meet in the middle, when
$i++just exceeds half the original@revstringslength.Actually, the
$i++is unnecessary, sincescalar @revstringswill be zero when the array is empty, so you just need: