Why can not my Perl code implement the reverse function?

advertisements

Here is my code named reverse.pl

#!usr/bin/perl -w
use 5.016;
use strict;

while(my $line=<>)
{
     my @array=();
     push (@array,$line);
     @[email protected];
     say @array;
}

Test file named a.txt

A B C D
E F G H
I J K L
M N O P
Q R S T

My command is perl reverse.pl a.txt

Why it can't implement the reverse function? I want to show the result is:

D C B A
H G F E

and so on.


Reverse in a scalar context reverses a scalar. Reverse in a list context reverses the list, but not each scalar within the list. You explicitly turn your scalar $line into a list with one item and then reverse the order of the items.

Try this:

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

while (my $line=<>) {
    chomp($line);
    say scalar reverse $line;
}

If you have an array and want to reverse each element (but not the elements), use map:

my @array = qw(Alpha Beta Gamma);
@array = map { scalar reverse $_ } @array;
print "@array\n";

If you want to do both (reverse each element and the elements themselves), do:

@array = map { scalar reverse $_ } reverse @array;

or:

@array = reverse map { scalar reverse $_ } @array;