Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

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.

Comment on Autogenerate descending arrays
Download Code
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 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?
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);

Back to Snippets Section

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: snippet [id://336412]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (6)
As of 2014-12-26 02:38 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (164 votes), past polls