This line clearly is doing too much at once. It can be broken down (as has already been explained) to
- my $test; and
- $test = 'a' if shift;
This may be you fooling around with Perl's syntax, or it may be a simplification of a real-world problem, but I'm hoping it's just fooling around.
Better would be
sub test
{
my $arg = shift;
my $test = '';
defined $arg and $test = 'a';
$test .= 'b';
return $test;
}
This is much longer, but I've removed the post-fix statement (personal preference); I have explicitly initialized
$test; and it's now clear that the steps are 1) initialize test; 2) set test to 'a' if there was an argument; 3) append 'b' to test; and 4) explicitly return the test value.
And the best part .. when you run it, you now get
b
b
as I expect you wanted.
My comments:
- I'm not a fan of post-fix -- I have to read it more than once to be sure I'm getting the right meaning.
- I don't mind writing stuff out so it takes a little longer to read, if the meaning or intent of the code is clearer.
- Yes, the explicit return is unnecessary in this context, but this then relies on the concatenation operation being the last line of code. Add something unrelated as the last statement, and suddenly the routine's returning an unexpected result.
- Code clarity matters. If you have to go back to some of your own code after six months and it takes time for you to decipher what's going on .. that's bad. Just make it clear, for your own sake, and for anyone else who has to read your code.
Alex / talexb / Toronto
Thanks PJ. We owe you so much. Groklaw -- RIP -- 2003 to 2013.