Evalutating a list in scalar context returns the last element in the list, not its length:
print scalar(1, 2, 3, 4, 3, 2, 1);
will print "1".
Because scalar is a unary operator, if you accidentally use a parenthesized list for the EXPR, this behaves as a scalar comma expression, evaluating all but the last element in void context and returning the final element evaluated in scalar context. This is seldom what you want.So what is actually happening here is (1, 2, 3, 4, 3, 2, 1) evaluates to 1, the last element in the list.
Output:use strict; use warnings; print "A: ", scalar(10, 20, 30, 40, 50, 60, 70), "\n"; # = scalar +(70) = scalar 70 = 70 print "B: ", scalar(70), "\n"; # + = scalar 70 = 70 print "C: ", scalar 70, "\n"; # + = 70 my $x = scalar(10, 20, 30, 40, 50, 60, 70); # = scalar +(70) = scalar 70 = 70 print "D: ", $x, "\n"; $x = (10, 20, 30, 40, 50, 60, 70); # = +(70) = 70 print "E: ", $x, "\n"; my @a = (10, 20, 30, 40, 50, 60, 70); print "F: ", scalar @a, "\n"; # = 7, the + length of @a
Useless use of a constant (10) in void context at D:\stuart\play\temp\ +pp.pl line 4. Useless use of a constant (20) in void context at D:\stuart\play\temp\ +pp.pl line 4. Useless use of a constant (30) in void context at D:\stuart\play\temp\ +pp.pl line 4. Useless use of a constant (40) in void context at D:\stuart\play\temp\ +pp.pl line 4. Useless use of a constant (50) in void context at D:\stuart\play\temp\ +pp.pl line 4. Useless use of a constant (60) in void context at D:\stuart\play\temp\ +pp.pl line 4. Useless use of a constant (10) in void context at D:\stuart\play\temp\ +pp.pl line 10. Useless use of a constant (20) in void context at D:\stuart\play\temp\ +pp.pl line 10. Useless use of a constant (30) in void context at D:\stuart\play\temp\ +pp.pl line 10. Useless use of a constant (40) in void context at D:\stuart\play\temp\ +pp.pl line 10. Useless use of a constant (50) in void context at D:\stuart\play\temp\ +pp.pl line 10. Useless use of a constant (60) in void context at D:\stuart\play\temp\ +pp.pl line 10. Useless use of a constant (10) in void context at D:\stuart\play\temp\ +pp.pl line 13. Useless use of a constant (20) in void context at D:\stuart\play\temp\ +pp.pl line 13. Useless use of a constant (30) in void context at D:\stuart\play\temp\ +pp.pl line 13. Useless use of a constant (40) in void context at D:\stuart\play\temp\ +pp.pl line 13. Useless use of a constant (50) in void context at D:\stuart\play\temp\ +pp.pl line 13. Useless use of a constant (60) in void context at D:\stuart\play\temp\ +pp.pl line 13. A: 70 B: 70 C: 70 D: 70 E: 70 F: 7
In reply to Re: Get the length of a list.
by zork42
in thread Get the length of a list.
by nbtrap
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |