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

my ($args) = @_; my %args = %{$args};
Is there a way to get this reduced to one line?

Replies are listed 'Best First'.
Re: Can I rewrite this code?
by toolic (Bishop) on Nov 21, 2018 at 20:53 UTC
    Assuming you don't need the $args scalar variable:
    my %args = %{ $_[0] };

Re: Can I rewrite this code?
by choroba (Cardinal) on Nov 21, 2018 at 20:53 UTC
    Not so nice, but possible:
    my %args = %{ $_[0] }; # or my %args = %{ +shift };

    Update: The dereference curly braces introduce a new scope, so declaring the variable inside doesn't make sense:

    my %args = %{ my $arg = shift }; # Here, $arg doesn't exist.
    ($q=q:Sq=~/;[c](.)(.)/;chr(-||-|5+lengthSq)`"S|oS2"`map{chr |+ord }map{substrSq`S_+|`|}3E|-|`7**2-3:)=~y+S|`+$1,++print+eval$q,q,a,
      and what does + in front of shift do?

        The + in front of shift tells Perl that you want the function shift and not a string "shift" as the hash key.

Re: Can I rewrite this code? (refaliasing)
by LanX (Saint) on Nov 21, 2018 at 21:23 UTC
    > Is there a way to get this reduced to one line?

    I doubt it's a good idea, since you might still want to pass more positional parameters. Otherwise you could just pass a list func(a=>1) with sub func { my %args = @_}

    But for completeness a solution with the new refaliasing feature

    use strict; use warnings; use Data::Dump qw/pp dd/; use feature qw/refaliasing/; no warnings "experimental::refaliasing"; sub tst { (\my %args) = @_; pp \%args; } tst({a=>1,b=>2});
    C:/Perl_524/bin\perl.exe d:/tmp/pm/refaliasing.pl { a => 1, b => 2 }

    Cheers Rolf
    (addicted to the Perl Programming Language :)
    Wikisyntax for the Monastery FootballPerl is like chess, only without the dice

Re: Can I rewrite this code?
by trippledubs (Deacon) on Nov 22, 2018 at 00:39 UTC
    shift->%*
    #!/usr/bin/env perl use strict; use warnings; use Data::Dumper; sub p { my %args = shift->%*; print Dumper \%args; } p({ cow => 'jump', over => 'moon' });
    produces
    $VAR1 = { 'cow' => 'jump', 'over' => 'moon' };
Re: Can I rewrite this code?
by ikegami (Patriarch) on Nov 22, 2018 at 00:23 UTC

    Yeah,

    my ($args) = @_;

    No need to make a copy of the hash!

      We don't know what the OP wants to do with the hash. If it is modified in the subroutine, it may need to be copied to prevent spooky action at a distance.

        They are free to ignore me in the unlikely situation that what I said doesn't apply to them.