in reply to mystery function & Odd number of elements in anonymous hash

Then func() returns an empty list. Perl flattens lists, so what you get is

my $hshref = { foo => bar => "baz" };

... which is a list of three elements, hence the warning. You will need to think long and hard about what the return value of func() is supposed to be, and what it should be instead when the original func() call returns an empty list.

Replies are listed 'Best First'.
Re^2: mystery function & Odd number of elements in anonymous hash
by Anonymous Monk on Jul 17, 2011 at 19:24 UTC

    I delved into the source code, and I believe the offending function ends with return wantarray ? @values : $values[0];.

    So hash building is in list context; the fat comma doesn't change a thing. Why not? Are my options to force scalar context, or append "|| 0" for a default value?

      The fat comma is just that, a fat comma. It stringifies the argument on its lefthand side if it is a bareword.

      Personally, I would use something like:

      my $foo = func(); my $hashref = { foo => $foo, bar => $bar };

        Thank you for your insights. I ended up writing a wrapper function to force context.

      Many functions return the empty list or undef as some sort of error condition. Are you sure @values ought to be empty?

      And how did adding a wrapper to force context solve the issue?

      CountZero

      A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity." - The Tao of Programming, 4.1 - Geoffrey James

        Many functions return the empty list or undef as some sort of error condition. Are you sure @values ought to be empty?

        The function in question is an accessor to a hash of sorts. It may return no values (=key does not exist) or multiple values.

        And how did adding a wrapper to force context solve the issue?

        return scalar func(@_); returns $values[0] which is undef in the case of no values which is fine and doesn't maim my hashes.