smoky has asked for the wisdom of the Perl Monks concerning the following question:

Hey Monks, I am rather new to Perl and I cannot quite get my head around why this code doesn't work:
my %p = ( outputdir => undef, rptfmt => 'html', rptname => undef, rptfile => '', title => undef, headers => [], data => [], stdout => 0, ); .... cut ..... my $rpt = Report->new($p{title}, $p{headers}, $p{data});
Module
sub new { my ($class,$title,$head,$data,$info) = @_; my $self = {}; bless ($self, ref ($class) || $class); $title ||= ""; $head = [] if !$head || ref $head ne 'ARRAY'; $data = [] if !$data || ref $data ne "ARRAY"; #$rows = $#{@$data} if $data || ref $data eq "ARRAY" || ref $$data +[0] ne "ARRAY"; my ($cols,$rows,@justify) = ($#{@$head},$#{@$data});
The module fails on the last line shown. The error is: Can't use string ("9") as an ARRAY ref while "strict refs" in use at .//Report.pm line 72. I am following an example I was given so it must be outside the module that is wrong.. Any ideas?

Replies are listed 'Best First'.
Re: Cannot find error : Can't use string ("9") as an ARRAY ref while "strict refs" ...
by Corion (Patriarch) on Mar 12, 2009 at 16:21 UTC

    The error is correct, because this expression: $#{@$head} does not do what you think it should. I assume you want the number of elements in @$head there. If head were an array, your code would look like this:

    sub new { ... my @head = (1,2,3); my $cols = $#head; ... };

    This already is wrong, because $#head is the index of the last element, so $cols will be 2, not 3. But to translate the code above, just follow References Quick Reference and write:

    sub new { ... my $head = [1,2,3]; my $cols = $#{$head}; ... };
Re: Cannot find error : Can't use string ("9") as an ARRAY ref while "strict refs" ...
by dreadpiratepeter (Priest) on Mar 12, 2009 at 16:24 UTC
    the $#{} construct is a deref and expects a reference. you passed it @$head, which is an array, not an arrayref. the array in scalar context gives the number of elements in it. since the $#{} construct needs a reference, which is a scalar, you are passing it 9


    -pete
    "Worry is like a rocking chair. It gives you something to do, but it doesn't get you anywhere."
      spot on guys, cheers!