in reply to Length of Array Passed as Reference
In addition to the excellent answers already given, I embed below a test program, for educational purposes, to show how to perform more thorough checking of function arguments. Such belt-and-braces checking of function arguments is probably over the top for most programs ... though there are times when you may feel it is warranted. Understanding the extra checks below should also help you better understand references in Perl.
use strict; use warnings; use Data::Dumper; use Carp; # Note: you could do extra manual checking of function arguments. # Not necessarily recommended: shown for educational purposes. # In example below, test_function takes exactly one argument, a ref to + an ARRAY sub test_function { my $narg = @_; $narg == 1 or croak "oops: this function takes exactly one argumen +t, a ref to an array (you provided $narg arguments)"; my $ref = shift; defined($ref) or croak "oops: argument is undef"; my $reftype = ref($ref); $reftype eq '' and croak "oops: argument should be a reference"; $reftype eq 'ARRAY' or croak "oops: argument should be ARRAY ref ( +not a '$reftype' ref)"; warn "reftype='$reftype'\n"; # Note: next line will die with "Not an ARRAY reference error" if +$ref is not an ARRAY ref warn "num elts=", scalar(@$ref), "\n"; # ... function body, process array ref $ref ... print Dumper($ref); } my @test_array = ([1, 2, 3], [4, 5, 6]); my %test_hash = ( "one" => 1, "two" => 2 ); # Can test function being called with invalid arguments... # test_function(); # oops, no arguments # test_function(undef); # oops, passed undef # test_function( \@test_array, 2 ); # oops, two arguments # test_function(1); # oops, one argument but not a re +f # test_function( @test_array ); # oops, array (not array ref) # test_function( \%test_hash ); # oops, hash ref (not array ref) test_function( \@test_array ); # Correct! One argument, array re +f!
Update: Minor improvements to argument checking, based on responses below; switched from die to Carp croak.
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^2: Length of Array Passed as Reference
by afoken (Canon) on Dec 10, 2020 at 08:21 UTC | |
by eyepopslikeamosquito (Bishop) on Dec 10, 2020 at 09:03 UTC | |
Re^2: Length of Array Passed as Reference
by tobyink (Canon) on Dec 10, 2020 at 09:21 UTC | |
by eyepopslikeamosquito (Bishop) on Dec 10, 2020 at 10:49 UTC |
In Section
Seekers of Perl Wisdom