Create an integer array downwards in Perl

Viewed 66

Is this a good way for create a downwards array from the range operator ..?

@array = reverse 1..9;
for my $i (@array) {
    print $i." "
}

# Output: 9 8 7 6 5 4 3 2 1

The question comes from the fact that the more obvious @array = 9..1; doesn't work

2 Answers

The main idea behind Perl is that there's more than one way to do it. It's fundamentally different from Python in that regard.

Your code works, but it has a few flaws. If you're learning to code in Perl right now, pick these best practices up early.

  • Always use strict and use warnings at the top of every program you write to help with debugging and catch errors early.
  • Declare variables with my in the smallest scope possible. That creates a lexical variable that only exists within that scope.

Now for the multiple ways, all of the following produce the same result.

use strict;
use warnings;

my @array1 = reverse 1..9;

foreach my $i ( @array1 ) {
  print "$i ";
}

# for and foreach can be used interchangeably 
for my $i (reverse 1..9) {
  print $i . ' ';
}

# post-fix for/foreach
print "$i " for @array1;

# join an array, eliminates trailing space
print join ' ', @array1;

# interpolate the array, automatically joins on $, variable, 
# which is a single space by default
print "@array1";

Two shorter versions

for  (reverse 1..9) {print "$_ "}

or

print "$_ " for  (reverse 1..9) 
Related