Optional parameters to regular expressions
pjf at perltraining.com.au
Sun Oct 27 23:12:33 CST 2002
On Mon, Oct 28, 2002 at 04:04:23PM +1100, Scott Penrose wrote:
> Is there a way I can do something like this.
> my $o = 'i';
> print "got it" if ($str =~ /fred/$o);
> ie: I want to be able to use a parameter to say it is case insensitive
> without having to use multiple if.
There sure is! You need to use non-matching parantheses, (?:), which
also allow you to turn regexp switches on and off. For your example:
print "got it" if $str =~ /(?$o:fred)/;
Switches places between the ? and : in your non-matching parentheses
are turned on for that sub-expression. Likewise, you can use "-i"
to turn case-insensitivity off until the end of the sub-expression.
All the best,
Paul Fenwick <pjf at perltraining.com.au> | http://perltraining.com.au/
Director of Training | Ph: +61 3 9354 6001
Perl Training Australia | Fax: +61 3 9354 2681
More information about the Melbourne-pm