Home > Blockchain >  Useless use of (/) in void context
Useless use of (/) in void context

Time:12-13

When I try this code:

use strict;
use warnings;
print (44 66)/2;

It gave me:

Useless use of division (/) in void context at p.pl line 3.

But, after some tries, it worked by adding extra outer parentheses around the expression like:

use strict;
use warnings;
print ((44 66)/2);

And it did work!

Can anybody explain why?

CodePudding user response:

Using Deparse will give you more information about how perl is parsing your code:

perl -MO=Deparse p.pl
Useless use of division (/) in void context at p.pl line 3.
use warnings;
use strict;
print(110) / 2;
p.pl syntax OK

Here you can see that the expression in the parens was evaluated as expected (66 44 = 110). But, then perl passes 110 as input to print, then tries to divide the output of print by 2.

Another helpful tool is diagnostics:

perl -Mdiagnostics p.pl
Useless use of division (/) in void context at p.pl line 3 (#1)
    (W void) You did something without a side effect in a context that does
    nothing with the return value, such as a statement that doesn't return a
    value from a block, or the left side of a scalar comma operator.  Very
    often this points not to stupidity on your part, but a failure of Perl
    to parse your program the way you thought it would. 

It's great that you enabled warnings because it alerted you that there could be a problem with your code. When we run the code, we get 110 as output, whereas you expected 55.

CodePudding user response:

The space between a function name and the opening parenthesis for the function call is optional. So when you write:

print (44 66)/2;
#    ^ optional space!

Perl is assuming that you want to divide print(44 66) by 2 and then ignore the answer. So Perl warns you about performing an unnecessary division operation.

# workaround
print( (44 66)/2 );

# other workaround
print  (44 66)/2;
  •  Tags:  
  • perl
  • Related