Search code examples
perlsubroutinestring-length

What happens when an array is passed to the Perl length subroutine?


This is my code:

my @list = qw (The quick brown fox jumps over the lazy Perl programmer); 
my @list1 = qw (Sparta F R I j h df dfsd dfsdf ); 
my @list2 = qw (The quick brown fox jumps over the lazy Perl programmer); 
print length(@list), "\n"; 
print length(@list1), "\n"; 
print length(@list2), "\n";

The output I get:

2
1
2

What's the reason behind the output? Shouldn't it give me the length of the first element?


Solution

  • This is very well documented here and here

    The length function always works on strings and it creates SCALAR context for its parameters. Hence if we pass an array as a parameter, that array will be placed in SCALAR context and it will return the number of elements in it.

    Calling length on an array returns the length of the number of elements in the array.

    Thus:

    • A 10-element array length(@list) returns 2 (length(10) == 2)
    • A 9-element array length(@list1) returns 1 (length(9) == 1)