Why am I getting a syntax error when I use "given"?
I am trying to run the following code:
foreach my $k (keys %rec) {
#switch for watchlist figures
given ($k) { #line 93
# Code omitted
when ("p") { #positive breakout
if ($row{cls} > $rec{$k}) {
$email .= "positive";
} # line 104
}
when ("n") { #negative breakout
if ($row{cls} < $rec{$k}) { #line 107
But I am getting syntax error:
syntax error at check_watch.pl line 93, near ") {"
syntax error at check_watch.pl line 104, near "}"
Unterminated <> operator at check_watch.pl line 107.
Why?
source to share
Since Perl 5 version 5.10 does not have keywords given
or when
, you are allowed to define UDFs with those names, which will of course have a different syntax. To avoid breaking backward compatibility with programs that do this given
and when
are only activated if you specifically request them by adding either
use 5.010;
or
use feature 'switch';
at the top of the lexical area in which you want to use keywords. Also, the semantics keep changing. For example, given
it was originally intended to use the $_
default lexical , but the lexical $_
turned out to be very bad for Perl 5, an issue they are still revising. At some point, given
stopped lexicalization $_
, but, of course, this is an incompatible change with the reverse change. when
(mostly) intended to be used ~~
, but this operator had very complex semantics in 5.10; they were revised once and there are plans to revise them again. (This is why the Perl 5 developers decided to simply mark all new features as "experimental" when they were first included in a development release).
Since they are experimental, to use them without warning, you also need to enable:
no if $] >= 5.017011, warnings => 'experimental::smartmatch';
or add dependency 5.18 and use
no warnings 'experimental::smartmatch';
or add a dependency on the CPAN module experimental
and use
use experimental 'smartmatch';
...
Now, on the other hand, Perl 5 developers (naturally) need people to use given
, when
and ~~
in non-production critical (or fully unit testing!) Code and give them feedback. So be sure to use them if you can.
source to share