user3525290
user3525290

Reputation: 1619

Subroutine not returning correct integer

I am passing data to a subroutine, but the subroutine is not returning the correct value.

test(5);

sub test {
    my $t = @_;
    return $t;
}

It should return 5 but is returning 2. I am using Mojolicious, but I am assuming that should not make a difference because it is just a function?

Upvotes: 2

Views: 120

Answers (1)

Dada
Dada

Reputation: 6661

my $t = @_ evaluates the array @_ in scalar context, and so sets $t to the size of @_.

From perldoc perldata

If you evaluate an array in scalar context, it returns the length of the array.

When you call test(5), @_ contains just (5), and so its length is 1. Using Mojolicious, you might be using a method call which also passes the package name or object reference as an additional argument of the subroutine, so your array will have a size of 2 instead of 1 as you describe.

If you want to retrieve the content of the array instead, use

my ($t) = @_;

If you're writing a method it should rather be

my $self = shift;
my ($t)  = @_;

but it depends on how the subroutine is called.

Upvotes: 8

Related Questions