Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 279
joe Avatar asked Feb 26 '10 14:02

joe


3 Answers

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.

like image 141
11 revs, 3 users 97% Avatar answered Nov 03 '22 02:11

11 revs, 3 users 97%


I guess you wanted to concatenate the string pieces to form the entire error message, so you'll have to use the dot instead of comma:

my $err = $soap_response->code. " ". $soap_response->string. "\n";
like image 22
codaddict Avatar answered Nov 03 '22 01:11

codaddict


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

or, better IMO:

return sprintf "%s %s\n", $soap_response->code, $soap_response->string;

See perldoc -f join and perldoc -f sprintf perldoc perlop.

Regarding the warning, see perldoc perlop and this note on the comma operator.

like image 3
Sinan Ünür Avatar answered Nov 03 '22 00:11

Sinan Ünür