Reputation: 2167
new to perl, trying to playing around with its syntax a bit, then I got this error message
$ perl testP
syntax error at testP line 3, near "$_ ("
Execution of testP aborted due to compilation errors.
for:
$_=$_+1 foreach $_ (@_);
Can anyone tell me what went wrong and how to fix it? thanks.
Upvotes: 1
Views: 1466
Reputation: 5641
$_
will get each different value of @_
on each iteration of the foreach, and the ++
operator will postincrement the values.
So something like this will work:
foreach (@_) {$_++;}
Note: $_++
is equivalent to $_ = $_ + 1
$_
and @_
are special variables in perl and they have an special behavior, in this case $_
in the context of a foreach loop takes the current value on each iteration.
Special variables are one of the complex and powerful parts of perl. You can get some more information about how they work on the special vars documentation.
Another thing is you shouldn't use a special variable as target of the foreach
as they most probably won't work as expected (see also the foreach documentation)
Upvotes: 0
Reputation:
foreach variable ( array ) is used in normal notation like:
foreach $_ ( @_ ) {
$_ = $_ + 1;
}
But you used the reverse notation, that is operation first, and loop then.
In this case you cannot provide variable name for the loop (which is useless anyway, since you're using default variable $_), and the loop should look:
$_ = $_ + 1 foreach @_;
Please also note that you can use for
instead of foreach
, and if you simply want to increment variable, you can do it with ++ operator, thus making it to:
$_++ for @_;
Upvotes: 10