kylex
kylex

Reputation: 14426

Why does printing a perl array give count?

I have the following function which returns an array:

sub getUsers() {
    @users[0] = 'test';
    @users[1] = 'test2';
    return @users;
}

@temp = getUsers();
$i = @temp;

print "There are $i users";

But when I print it out, it appears as the number 2 (the count of the array). What's happening?

Upvotes: 1

Views: 294

Answers (2)

David W.
David W.

Reputation: 107060

When you use an array in a scalar context, the array returns the number of items in the array.

From the Perldoc on Perldata

List assignment in scalar context returns the number of elements produced by the expression on the right side of the assignment...

When you say:

$i = @temp;

You are taking a list and attempting to assign it to a scalar variable. You are using that array in scalar context. Thus, you get the size of the array. (Not the largest index. That's what $#temp will get you.

You can use the scalar function to force an array in scalar context shen it might not otherwise be: ` print "There are " . scalar @foo . " items in the array\n";

The print function can take a list of times and not just a single string. It then uses the value of the variable $,to join the array.

If you want a list of items, use the join to join a list into a single string:

print "There are " . scalar @foo . " items in the array\n";
print "They are " . join ( ", " $foo ) . ".\n";

Upvotes: 0

ysth
ysth

Reputation: 98398

$i = is a scalar assignment, giving the right side of the assignment scalar context; when you mention an array in scalar context, it returns its length.

Upvotes: 11

Related Questions