What's the problem with following. I am getting $attribute not defined
error.
if (my $attribute = $Data->{'is_new'} and $attribute eq 'Y') {
}
Substitution Operator or 's' operator in Perl is used to substitute a text of the string with some pattern specified by the user.
There is a strange scalar variable called $_ in Perl, which is the default variable, or in other words the topic. In Perl, several functions and operators use this variable as a default, in case no parameter is explicitly used.
$1 equals the text " brown ".
=~ is the Perl binding operator. It's generally used to apply a regular expression to a string; for instance, to test if a string matches a pattern: if ($string =~ m/pattern/) {
You're being too clever. Just do this:
my $attribute = $Data->{'is_new'};
if (defined $attribute && $attribute eq 'Y') { ... }
The problems are twofold:
)
in your ifmy
in expression context binds very tightly; $attribute
is not in lexical scope until the body of the conditional statement that contains it, so the other branch of the and
cannot access it. You need to lift it to the containing context, as in my example.use strict;
would have found the problem.
$ perl -e'use strict; my $attribute = "..." and $attribute eq "Y";'
Global symbol "$attribute" requires explicit package name at -e line 1.
Execution of -e aborted due to compilation errors.
A my
declaration only has an effect on subsequent statements, not the the statement in which the declaration is is located. (Same goes for the our
and local
declarations.) That means the $attribute
that you create with my
and to which you assign is a different variable than the $attribute
you compare to Y
. You want
my $attribute = $Data->{'is_new'};
if ($attribute eq 'Y') { ... }
Now, if $Data->{is_new}
doesn't exist or is undefined, $attribute
will be undefined, and comparing it to Y
will issue a warning. You can avoid this warning as follows:
my $attribute = $Data->{'is_new'};
if (defined($attribute) && $attribute eq 'Y') { ... }
Alternatively: (5.10+)
my $attribute = $Data->{'is_new'};
if (($attribute // '') eq 'Y') { ... }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With