Stories
Slash Boxes
Comments
NOTE: use Perl; is on undef hiatus. You can read content, but you can't post it. More info will be forthcoming forthcomingly.

All the Perl that's Practical to Extract and Report

use Perl Log In

Log In

[ Create a new account ]

nik (3476)

nik
  nikc@cpan.org
AOL IM: nikclayton (Add Buddy, Send Message)

Journal of nik (3476)

Thursday November 16, 2006
08:48 AM

"..", LHS larger than RHS gives empty list. Why?

[ #31626 ]

From perlop

Binary ".." is the range operator, which is really two different operators depending on the context. In list context, it returns a list of values counting (up by ones) from the left value to the right value. If the left value is greater than the right value then it returns the empty list.

(emphasis added). So:

@a = (1 .. 3); # @a = (1, 2, 3)
@b = (3 .. 1); # @b = (), *not* @b = (3, 2, 1)
@c = reverse (1 ..3); # @c = (3, 2, 1)

Why is this? I had occasion to do this the other day, and my first cut at the code did the equivalent of @b above, instead of @c, which led to a few moments headscratching.

It struck me as odd that Perl, which so often DWIMs, gets it wrong here.

The Fine Print: The following comments are owned by whoever posted them. We are not responsible for them in any way.
 Full
 Abbreviated
 Hidden
More | Login | Reply
Loading... please wait.
  • If I want the numbers 1 through $x, and x might be zero or less (in which case I would want an empty list), then I'd rather not have to say if ($x >= 1) ..., I can just say (1..$x). I think it was felt that that was the more common case than wanting the reverse list.
    • Indeed. The current behaviour is sometimes annoying, but never surprising. The alternative would be sometimes convenient, but often surprising.