6.11. Testing for a Valid PatternProblemYou want to let users enter their own patterns, but an invalid one would abort your program the first time you tried to use it. Solution
Test the pattern in an do { print "Pattern? "; chomp($pat = <>); eval { "" =~ /$pat/ }; warn "INVALID PATTERN $@" if $@; } while $@; Here's a standalone subroutine that verifies whether a pattern is valid. sub is_valid_pattern { my $pat = shift; return eval { "" =~ /$pat/; 1 } || 0; }
That one relies upon the block returning Discussion
There's no end to patterns that won't compile. The user could mistakenly enter The tiny program in Example 6.9 demonstrates this. Example 6.9: paragrep#!/usr/bin/perl # paragrep - trivial paragraph grepper die "usage: $0 pat [files]\n" unless @ARGV; $/ = ''; $pat = shift; eval { "" =~ /$pat/; 1 } or die "$0: Bad pattern $pat: $@\n"; while (<>) { print "$ARGV $.: $_" if /$pat/o; }
That
You could encapsulate this in a function call that returns 1 if the block completes and 0 if not as shown in the Solution section. Although $pat = "You lose @{[ system('rm -rf *')]} big here"; If you don't wish to provide the user with a real pattern, you can always metaquote the string first: $safe_pat = quotemeta($pat); something() if /$safe_pat/; Or, even easier, use: something() if /\Q$pat/;
But if you're going to do that, why are you using pattern matching at all? In that case, a simple use of
By letting the user supply a real pattern, you give them the power into do interesting and useful things. This is a good thing. You just have to be slightly careful, that's all. Suppose they wanted to enter a case-insensitive pattern, but you didn't provide the program with an option like
grep
's
-i
option. By permitting full patterns, the user can enter an embedded
What happens if the interpolated pattern expands to nothing? If
Even if you use See Also
The |
|