Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Perl's strict not let me pass a parameter hash?

Tags:

perl

strict

I hava a perl subroutine where i would like to pass parameters as a hash (the aim is to include a css depending on the parameter 'iconsize').

I am using the call:

get_function_bar_begin('iconsize' => '32');

for the subroutine get_function_bar_begin:

use strict;
...
sub get_function_bar_begin
{
    my $self = shift;
    my %template_params = %{ shift || {} };

    return $self->render_template('global/bars   /tmpl_incl_function_bar_begin.html',%template_params);
}

Why does this yield the error message:

Error executing run mode 'start': undef error - Can't use string ("iconsize") as a HASH ref while "strict refs" in use at CheckBar.pm at line 334

Am i doing something wrong here? Is there an other way to submit my data ('iconsize') as a hash?

(i am still new to Perl)

EDIT: Solution which worked for me. I didn't change the call, but my function:

sub get_function_bar_begin
{
    my $self = shift;
    my $paramref = shift;
    my %params = (ref($paramref) eq 'HASH') ? %$paramref : ();
    my $iconsize = $params{'iconsize'} || '';

    return $self->render_template('global/bars/tmpl_incl_function_bar_begin.html',
        {
            'iconsize'  => $iconsize,
        }
    );
}
like image 381
Thariama Avatar asked Nov 28 '22 19:11

Thariama


1 Answers

You are using the hash-dereferencing operator ( %{ } ) on the first argument of your parameter list. But that argument is not a hash reference, it's just the string 'iconsize'. You can do what you want by one of two ways:

Pass an anonymous hash reference:

get_function_bar_begin( { 'iconsize' => '32' } );

Or continue to pass a normal list, as you are right now, and change your function accordingly:

sub get_function_bar_begin {
    my $self = shift;
    my %template_params = @_;
}

Notice in this version that we simply assign the argument list directly to the hash (after extracting $self). This works because a list of name => value pairs is just syntactic sugar for a normal list.

I prefer the second method, since there's no particularly good reason to construct an anonymous hashref and then dereference it right away.

There's also some good information on how this works in this post: Object-Oriented Perl constructor syntax.

like image 65
friedo Avatar answered Dec 06 '22 09:12

friedo