drake50 has asked for the wisdom of the Perl Monks concerning the following question:

The following works great:
perl -e 'foreach $index (5..9, 12..18) { print "$index\n" }'
But, is there a nice way to do this-->
perl -e 'foreach $index (9..5, 12..18) { print "$index\n" }'

Replies are listed 'Best First'.
Re: Perl range
by FunkyMonk (Bishop) on Oct 03, 2007 at 19:23 UTC
    perl -e 'foreach $index (reverse( 5..9 ), 12..18) { print "$index\n" } +' #update: or perl -e 'print "$_\n" for reverse( 5..9 ), 12..18'

      Nice. I don't know why I didn't think of reverse!
        That explains your short node title. If you thought, "hey I want the reverse version of the range...", you might have put a title such "Reversing Perl range". In this case, there was a great chance that you would resolve it yourself without firing a node. The good side is you generated a pretty high attention and resulted in a pretty interesting thread :-)

        Update: I would FP this myself.


        Open source softwares? Share and enjoy. Make profit from them if you can. Yet, share and enjoy!

Re: Perl range
by johngg (Canon) on Oct 03, 2007 at 20:29 UTC
    You can also use the -l switch to automatically append a line terminator for each print operation, thus allowing print to output $_ by default.

    perl -le 'print for reverse(5 .. 9), 12 .. 18;'

    I hope this is of use.

    Cheers,

    JohnGG

Re: Perl range
by mwah (Hermit) on Oct 03, 2007 at 19:55 UTC
    another one:
    perl -e 'print abs,"\n" for -9..-5, 12..18'

    mwa

       perl -le 'for $i (map abs, -9..-5, 1..3) { print $i }'




      perl -e '$,=$",$_=(split/\W/,$^X)[y[eval]]]+--$_],print+just,another,split,hack'er
Re: Perl range
by ikegami (Patriarch) on Oct 03, 2007 at 20:09 UTC

    And a generic solution:

    for ([9,5], [12,18]) { my ($i, $j) = @$_; my $f = ($i <= $j ? 1 : -1); for ($f*$i .. $f*$j) { my $index = $f*$_; print("$index\n"); } }