Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

Re: Length of Array Passed as Reference

by GrandFather (Saint)
on Dec 10, 2020 at 02:01 UTC ( [id://11124921]=note: print w/replies, xml ) Need Help??


in reply to Length of Array Passed as Reference

The key issue is your parameter assignment in test_function. @_ is an array list so assignment in a scalar context will get you the length of the array list - in this case 1 because there is a single parameter passed to test_function. The fix is to use a list assignment:

use warnings; use strict; use feature qw/say /; my @test_array = ([1, 2, 3], [4, 5, 6]); test_function(\@test_array); sub test_function { my ($ref_array) = @_; say scalar @$ref_array; }

Prints:

2

Note too that in Perl since last century you don't need to call subs using &. In fact doing so can cause some very nasty to find bugs.

Dumping $ref_array instead of @_ may have helped you pick up the error.

Update: corrected brain fart - thanks haukex

Optimising for fewest key strokes only makes sense transmitting to Pluto or beyond

Replies are listed 'Best First'.
Re^2: Length of Array Passed as Reference
by haukex (Archbishop) on Dec 10, 2020 at 09:16 UTC
    @_ is a list so assignment in a scalar context will get you the length of the list

    I think the distinction between list and array is important here. An array in scalar context returns its length, a literal list in scalar context returns its last element. @_ is an array.

Re^2: Length of Array Passed as Reference
by Leudwinus (Scribe) on Dec 10, 2020 at 02:26 UTC

    Thank you as well for the very quick response!

    The reason I did y $ref_array = @_ was because I was passing an array reference to the subroutine but didn't make the connection between the scalar assignment (which is what I did) and list assignment (which is what I should have done).

    I don't think I will ever post a non-reference-related question here based on my history but I swear, I am trying!

      I use the list assignment mantra as a matter of course when accessing parameters passed into a sub so anything else as the first line of the body of a sub looks strange to me. Doing the parameter assignments in a single hit up front makes it easier to see what should be passed into the sub. Getting into the habit of solving the same problem in the same way is often a Good Thing.

      Optimising for fewest key strokes only makes sense transmitting to Pluto or beyond

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11124921]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others goofing around in the Monastery: (7)
As of 2024-04-25 15:33 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found