Why 'z'..'a' is not empty?

P

Peng Yu

Hi,

The following code shows that 'z'..'a' is not empty. But perlop says
the following. So it should return empty list. Does anybody know why
'z'..'a' is not empty?

"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."

~/linux/test/perl/man/perlop/dot_dot/list_context$ cat main.pl
#!/usr/bin/env perl

use warnings;

print join(',', 1..10), "\n";
print join(',', 10..1), "\n";
print join(',', 'a'..'z'), "\n";
print join(',', 'z'..'a'), "\n";

~/linux/test/perl/man/perlop/dot_dot/list_context$ ./main.pl
1,2,3,4,5,6,7,8,9,10

a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z
z
~/linux/test/perl/man/perlop/dot_dot/list_context$ perl --version

This is perl 5, version 14, subversion 2 (v5.14.2) built for darwin-
thread-multi-2level
(with 1 registered patch, see perl -V for more detail)

Copyright 1987-2011, Larry Wall

Binary build 1402 [295342] provided by ActiveState http://www.ActiveState.com
Built Oct 7 2011 15:58:41

Perl may be copied only under the terms of either the Artistic License
or the
GNU General Public License, which may be found in the Perl 5 source
kit.

Complete documentation for Perl, including FAQ lists, should be found
on
this system using "man perl" or "perldoc perl". If you have access to
the
Internet, point your browser at http://www.perl.org/, the Perl Home
Page.
 
C

C.DeRykus

This happens because of the way .. works on non-numeric values. It uses

the properties of ++ on strings, which means that "z" will roll over to

"aa" rather than to "{", but that also means that it can't compare the

endpoints before starting because that would make "z".."ab" return the

empty list.

And to expand on this, IIUC, .. gets really
twisty if there's magical ++ on strings:

perl -lE 'say join(",", "m" .. "a")'
m,n,o,p,q,r,s,t,u,v,w,x,y,z

Similarly:
perl -lE 'say join(",", "y" .. "a")'
y,z


Intuitively, you might think just as with
numeric operands, this should yield the empty list since "m" (or "y" in the latter case) is "greater" than "a" and But, since they're strings, it'll ++ until "z" falls over the edge
to "aa" which is longer than "a".


from perlop:

If the final value specified is not in the
sequence that the magical increment would
produce, the sequence goes until the next
value would be longer than the final value
specified.


So, Peng's 'z' to 'a' example ++'s to 'aa'
which it's longer than 'a' then stops which
leaves only the initial 'z' as output.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,016
Latest member
TatianaCha

Latest Threads

Top