http://www.perlmonks.org?node_id=336412

The Perl range operator '..' is often used to quickly fill in arrays like so: @arr = ( 1..9 );. Unfortunately that only works when the left argument is smaller than the right argument and you can only make an array with ascending values. But what if you want descending values?
@array = ( 7..1 ); # returns an empty array @array = map { $_ * -1 } ( -7..-1 ); # When generating the array you are technically going # up from a large negative to a small negative. # Then, you multiply each value by -1 and assign # to @array. Works like a charm.

Replies are listed 'Best First'.
Re: Autogenerate descending arrays
by jweed (Chaplain) on Mar 13, 2004 at 21:08 UTC
Re: Autogenerate descending arrays
by pbeckingham (Parson) on Mar 13, 2004 at 21:12 UTC

    How about simply reversing the resultant range?

    @array = reverse (1..7);

Re: Autogenerate descending arrays
by TomDLux (Vicar) on Mar 13, 2004 at 21:25 UTC

    Dunno if it makes it more familiar, my instinct was to put the reverse inside the parenthesese.

    My logic kinda runs:

    • Create a sequence, 1..7.
    • Reverse it.
    • Make it into a list to assign to the array.

    Of course, having reverse() return a list works, too.

    --
    TTTATCGGTCGTTATATAGATGTTTGCA

Re: Autogenerate descending arrays
by kappa (Chaplain) on Mar 14, 2004 at 21:57 UTC
    This is weird, but looks and feels somewhat cool :) And to all commenters, TMTOWTDI, btw.

    On to the code. There's no need to do multiplications to negate a number.

    @a = map { -$_ } (-7 .. -1);
Re: Autogenerate descending arrays
by bl0rf (Pilgrim) on Mar 14, 2004 at 21:52 UTC
    aah! I completely forgot about reverse!
    Thank you fellow monks for your feedback, testing also shows that reverse is twice as fast as my method. I'm happy there's more than one way to do it ( or anything ).

      By the way, using reverse is faster because this case is optimized as the action mentioned in the subject is very common :)
        How is it optimized?