http://www.perlmonks.org?node_id=571305

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

I have a subroutine that that I am passing named parameters into and receive the following error:

Can't use string ("1") as a HASH ref while "strict refs"

Here is the code snippet:

use strict; use DBI; my @record = qw(adam baker code dog); @record = validate_record_length({record => \@record, recl => '18'}); sub validate_record_length { my $args = @_; my @record = $args->{record}; my $recl = $args->{recl}; my $record_size = @record; for (my $i = $record_size; $i < $recl; $i++){ $record[$i] = ''; } return @record; }

The subroutine just takes a record as an array from another process and makes sure that it has enough fields though the filled out fields are null. There are other subroutines in the actual code setup before this one and as you can tell I am using the DBI module.

Seeker of knowledge
sxmwb

Replies are listed 'Best First'.
Re: subroutine passing array as named parameter
by zigdon (Deacon) on Sep 05, 2006 at 18:58 UTC
    You're evaluating @_ in scalar context - which returns the number of items (1 in this case). Try forcing list context instead:
    sub validate_record_length { my ($args) = @_; ...

    -- zigdon

      Thank you. I feel dumb now. I copied the code and for some reason dropped the parans. This solved the problem.

      Thanks for the help and I keep learning a lot from everyone.

      Seeker of knowledge

      sxmwb

Re: subroutine passing array as named parameter
by jdporter (Paladin) on Sep 05, 2006 at 18:58 UTC

    So you're passing a hash by reference, and one of its elements has key "record", and its corresponding value is an array reference.

    You need to deal with the array reference in the sub. That is,

    $args->{record}
    is a reference, so you need to do
    my @record = @{ $args->{record} };

    We're building the house of the future together.
Re: subroutine passing array as named parameter
by gellyfish (Monsignor) on Sep 05, 2006 at 18:58 UTC

    You want to do:

    my ($args) = @_;
    The
    my $args = @_;
    Is setting $args to the length of @_

    /J\

Re: subroutine passing array as named parameter
by neosamuri (Friar) on Sep 05, 2006 at 19:47 UTC

    In this case you could also use shift:

    my $args = shift

    This method I think makes the subroutines more readable. As well as preventing the problem that you ran into on that line.

    Another thing which could be done is:

    my $args = {@_};

    Then just pass in the hash as an array

    @record = validate_record_length(record => \@record, recl => '18');