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

I'm attempting to return a hash from a subroutine.
sub saveAccountAccess { my $p = shift; my $input = $p->{'input'}; my $session = $p->{'session'}; my $error = {}; . . . if (defined $nickname and length($nickname) != 0) { # Check for duplicates error $duplications = &LookForDups($nickname, $p); if ($duplications){ return 'nick_name' => 1, } &updateNickname($nickname, $p);
Several other returns are of the same form in this function and each returns a Hash. My return is just "1"; a string. This is an error. Thanks!

Replies are listed 'Best First'.
Re: Returning Hash from subroutine of form 'var' => 1,
by Athanasius (Archbishop) on Jun 15, 2015 at 15:02 UTC

    Hello NodXof, and welcome to the Monastery!

    You are actually returning a list, not a hash. Now, if the subroutine is called in list context, the list will indeed be returned; but if (as appears to be the case) it’s called in scalar context, only the right-most element of the list will be returned (see Comma Operator). In this case, the right-most element is 1. On context, see Context tutorial by kyle.

    You will find it easier to return a hash reference from the sub. For example:

    if ($duplications){ return { 'nick_name' => 1 }; }

    Of course, you will then need to dereference the hash reference upon returning from the sub:

    my $href = saveAccountAccess (...); my ($key, $val) = %$href;

    See perlreftut.

    Updates: Added references to the Perl documentation and to the Monastery’s tutorial on context in Perl.

    Hope that helps,

    Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,

Re: Returning Hash from subroutine of form 'var' => 1,
by kroach (Pilgrim) on Jun 15, 2015 at 15:03 UTC

    Could you please provide more context (the assignment and use of the returned value and a full working example)?

    The return itself seems fine. The following code works:

    use strict; use warnings; use Data::Dumper; sub ret_hash { return nick => 1; } my %hash = ret_hash(); print Dumper(\%hash);

    Perhaps you are trying to return a hash reference. If you assign the function result to a scalar you should return a reference. Anonymous hashes can be created with {}:

    use strict; use warnings; use Data::Dumper; sub ret_hash { return {nick => 1}; } my $hash = ret_hash(); print Dumper($hash);
Re: Returning Hash from subroutine of form 'var' => 1,
by hippo (Archbishop) on Jun 15, 2015 at 15:04 UTC

    To return a hash:

    return ('nick_name' => 1);

    To return a hashref:

    return {'nick_name' => 1};
      # Check for duplicates $duplications = &LookForDups($nickname, $p); if ($duplications){ return {'nick_name' => 1,} }
      This did the trick!