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 argument, 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 ref # 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 ref!