Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid

Autogenerate descending arrays

by bl0rf (Pilgrim)
on Mar 13, 2004 at 20:58 UTC ( #336412=snippet: print w/replies, xml ) Need Help??
Description: 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.


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?
Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: snippet [id://336412]
[marto]: erix [id://1193617| pretty much
[marto]: err pretty much

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (8)
As of 2017-06-29 13:04 GMT
Find Nodes?
    Voting Booth?
    How many monitors do you use while coding?

    Results (665 votes). Check out past polls.