1D0-437 · Question #31
Consider the following lines of code: sub mySub { $_ = @_[1]; $a = shift; $b = shift; return $a $b $_; } mySub(1,2,3); What is the output of these lines of code?
The correct answer is A. No output results from this code. See the full explanation below for the reasoning.
Question
Consider the following lines of code:
sub mySub { $_ = @[1]; $a = shift; $b = shift; return $a * $b * $; } mySub(1,2,3); What is the output of these lines of code?
Options
- ANo output results from this code.
- B6
- C2
- D4
How the community answered
(55 responses)- A84% (46)
- B9% (5)
- C2% (1)
- D5% (3)
Community Discussion
5The answer is A, no output, because the sub just returns a value but nothing ever prints it, there is no print or say statement anywhere in the code so the result of 1 times 2 times 2 just gets thrown away. Easy trap on this exam, they want you to notice the missing print, not get distracted doing the math on the multiplication.
Luis is right that the missing output statement is the trap, but worth noting for people still learning the language that "no output" and "no return value" are two different things, the sub does return 4 to whatever called it, it just happens that nothing in this snippet does anything with that returned value.
Right, no output because the return value is never printed.
Yeah exactly, and it is worth pointing out that in interactive mode Python does print return values automatically, so this trips a lot of people up when they move their code into a script file for the first time.
So my senior walked me through this one and it clicked, the sub does all that math and actually returns a value, but since the call is just sitting there with nothing capturing or printing it, nothing ever shows up on screen, which is why the answer is A. Does the return value just get thrown away completely in Perl when you do not assign it or wrap it in a print, or is there some edge case where it might still surface somewhere?