Re: in the elemetns of programming perl , I need help with 2 lines that I don't understand
[email protected] (Richard Lee)
| Newsgroups | perl.beginners |
|---|---|
| Message-ID | <[email protected]> |
Rob Dixon wrote:
> qr// isn't often necessary, as they are usually defined, compiled and used at
> the same point, like constants. However, if you have a regex that you need to
> use in several places in your code then it can be useful to declare it
> separately, like
>
> my $bracketed = qr/^\{.*\}$/;
>
> foreach my $element (@a) {
> print if $element =~ $bracketed;
> }
>
> foreach my $element (@b) {
> print if $element =~ $bracketed;
> }
>
> It can also be useful for building complex regexes:
>
> my $number = qr/\b[0-9]+\b/;
> my $alphachar = qr/[A-Z]/i;
> my $identifier = qr/\b$alphachar\w*\b/;
> my $value = qr/(?:$number|$identifier)/;
> my $assignment = qr/$identifier\s*=\s*$value/;
>
>
> As a separate idea, the /o qualifier on a regex asks that it is compiled only
> the first time it is encountered. This makes no difference unless it contains
> interpolated variables, but the behavior can be seen in this program
>
> use strict;
> use warnings;
>
> foreach my $char ('A' .. 'Z') {
> my $re = qr/$char/o;
> print "$char" if $char =~ $re;
> }
> print "\n";
>
> foreach my $char ('A' .. 'Z') {
> my $re = qr/$char/;
> print "$char" if $char =~ $re;
> }
> print "\n";
>
>
> HTH,
>
> Rob
>
Thank you Rob and Chas,
I understand now.
Rob, your last code is very helpful!!