Okay开发者_如何学C, so there is an input form, with 4 text boxes. I get the input using CGI.pm:
my $exc0 = param('exclude0') || 'a';
my $exc1 = param('exclude1') || 'a';
my $exc2 = param('exclude2') || 'a';
my $exc3 = param('exclude3') || 'a';
The reason I had to include the || 'a'
is to allow it to work if there was no input. Is there a safer way to do this?
It gets called later on in a regex:
next if ($totalmatch->[2] =~ /\b$exc0\b/i);
next if ($totalmatch->[2] =~ /\b$exc1\b/i);
next if ($totalmatch->[2] =~ /\b$exc2\b/i);
next if ($totalmatch->[2] =~ /\b$exc3\b/i);
Where $totalmatch->[2]
is a sentence. If I don't check for no input, when there isn't an input no matches come up (a.k.a. it includes $exc
in every case). I'd guess this is because there is an undef or space in every sentence?
What I've tried is || ''
and I suppose I could use a if ($exc0)
or a if defined()
or eq ''
but just looking for help.
Thanks a lot for your time.
If you don't do use warnings
and don't do the || 'a'
you should get a warnings: Use of uninitialized value at ...
It's best practice in perl (or any language, for that matter) to check for the existence of a variable before you use it in a function, or in this case, a regular expression, unless there is a specific reasons of it being null being a desirable possibility.
Your should really get rid of the || 'a'
and do this:
next if (length($exc0) and $totalmatch->[2] =~ /\b$exc0\b/i);
next if (length($exc1) and $totalmatch->[2] =~ /\b$exc1\b/i);
next if (length($exc2) and $totalmatch->[2] =~ /\b$exc2\b/i);
next if (length($exc3) and $totalmatch->[2] =~ /\b$exc3\b/i);
You don't want to use defined()
here because ''
is defined, and you'll still have the problem of it matching.
精彩评论