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

What is the correct way to pass a hash to a subroutine separately from a few strings? I have been using the following method,

sub generate { my $record = shift; my $status = shift; my %data = %{$_[0]}; ...

However, that brings up an "Always unpack @_ first" error with perlcritic --stern and therefore I wonder if there is a more appropriate method.

Replies are listed 'Best First'.
Re: Passing a hash plus some strings to a subroutine
by Fletch (Bishop) on Dec 17, 2025 at 15:02 UTC

    I'd maybe do something like this, or just name it $data and use $data->{'foo'} rather than having to have an actual hash locally (unless you're worried about altering the original through the ref).

    sub generate { my( $record, $status, $_data ) = @_; my %data = %{ $_data }; ... }

    The cake is a lie.
    The cake is a lie.
    The cake is a lie.

Re: Passing a hash plus some strings to a subroutine
by hippo (Archbishop) on Dec 17, 2025 at 15:25 UTC

    It's just moaning about your use of individually shifting the args. This passes perlcritic --stern for me:

    sub generate { my ($record, $status, %data) = @_; return; }

    🦛

      Nothing wrong with shifting. Easier to provide defaults and comments. And then there's the newish signature feature. Take perlcritic's critiques with a grain a salt, and adjust them to your liking.

      Not the same thing tho.

      The OP is passing a hashref, but you are un- and repacking a hash as list of keys and values.

      Cheers Rolf
      (addicted to the Perl Programming Language :)
      see Wikisyntax for the Monastery

Re: Passing a hash plus some strings to a subroutine
by LanX (Saint) on Dec 17, 2025 at 16:11 UTC
    It depends on ...

    • which version of perl you are using
    • how much you care about backwards compatibility
    • if this semantic matters (passing a hashref and flat-copying it)
    update

    but yeah, the real problem here is perlcritic enforcing old PBP rules here.

    Not sure how it handles newer mechanisms.

    Cheers Rolf
    (addicted to the Perl Programming Language :)
    see Wikisyntax for the Monastery