How can I resolve this case of "Useless use of a variable in a void context"?

joe picture joe · Feb 26, 2010 · Viewed 20.6k times · Source

How can I resolve this case of "Useless use of a variable in a void context"?

For example:

  my $err = $soap_response->code, " ", $soap_response->string, "\n";
  return $err;

I get warnings like "Useless use of a variable in a void context"? Why? How can I resolve it?

Answer

Eugene Yarmash picture Eugene Yarmash · Feb 26, 2010

In case you want to concatenate the arguments, use the "." operator or join:

my $err = $soap_response->code. " ". $soap_response->string. "\n";
my $err = join '', $soap_response->code, " ", $soap_response->string, "\n";

Next is why Perl gives you warnings.

You're assigning to a scalar variable $err, and the right-hand side of the assignment is evaluated in scalar context.

Binary "," is the comma operator. In scalar context it evaluates its left argument in void context, throws that value away, then evaluates its right argument in scalar context and returns that value.

Evaluating a variable or a constant and throwing that value away is useless. And perl warns you about this.

FYI: Another possible issue with your code:

my $err = $soap_response->code, " ", $soap_response->string, "\n";

The assignment has higher precedence so that is:

(my $err = $soap_response->code), " ", $soap_response->string, "\n";

See Perl operators and precedence and the Comma operator for more information.