Implementing a simple tac program

I tried to solve an exercise in Schwartz's “Learning Perl” when I came across an unexpected result in the code I wrote. I was wondering what I did wrong.

Qn: run a simple tac similar to the unix utility.

My decision:

#!/usr/bin/perl
use strict;
use warnings;

my @array;
while (<>) {
    push @array, $_;
}

foreach ($#array..0) {
    print $array[$_];
}

Implementation with: $ ./tac list

where the list contains:

$ cat list 
An apple 
Blue boys
Coy cows
Dreary ducks!

does not display the result.

$ ./tac list
$
+4
source share
3 answers

Your problem is the loop counter foreach. You cannot retreat like that.

Instead, you can:

while (@array) {
    print pop @array;
}

or simply:

print pop @array while (@array);

while (@array)will evaluate @arrayin a scalar context, which means that the size of the array will be checked. When the size reaches zero, the loop ends.


Since this is perl, there are, of course, a million ways to do this. Another variant:

print for reverse @array

... , unshift:

#!/usr/bin/perl
use strict;
use warnings;

my @array;
while (<>) {
    unshift @array, $_;
}

print for @array;

... :

#!/usr/bin/perl
use strict;
use warnings;

print reverse <>;

Perl!

+4

:

$ perl -e 'foreach my $i (10..0) { print "$i\n"; }'
$

:

#!/usr/bin/perl
use strict;
use warnings;

my @array = <>;

foreach (0..$#array)
{
    print $array[$#array - $_];
}
+2

You cannot countdown in a loop foreach. You can use reverseto achieve the same task

my @array = <>;

foreach (reverse 0..$#array)
{
    print $array[$_];
}
+1
source

Source: https://habr.com/ru/post/1541894/


All Articles