At 12:44 PM +0800 2/9/12, lina wrote:
#!/usr/bin/perl
use strict ;
my @strings = ( "Fred and Barney",
                "Gilligan or Skipper",
                "Fred and Ginger"
              );
foreach my $string (@strings)
        {
        $string =~ m/(\S+)(and|or)(\S+)/;

        print "\$1: $1\n\$2: $2\n\$3: $3\n";
        print "-" x 10, "\n";
        } ;

Why the results is:

$ ./grouping_example.pl
$1:
$2:
$3:
----------
$1:
$2:
$3:
----------
$1:
$2:
$3:
----------

no value output?

The reason is that your match did not succeed (as others have pointed out and given you regular expressions that work).

It is important to test the success of the match before you use the captured values. You should also add 'use warnings;' to your program. Had you done that, Perl would have told you that no values were captured.

If the match is not successful, then Perl will not reset the capture variables:

__program__

#!/usr/bin/perl
use strict;
use warnings;

my @strings = (
  "FredandBarney",    # spaces removed so match will succeed
  "Gilligan or Skipper",
  "Fred and Ginger"
);
foreach my $string (@strings) {
  $string =~ m/(\S+)(and|or)(\S+)/;
  print "<$1> <$2> <$3>\n";
};

__output__

<Fred> <and> <Barney>
<Fred> <and> <Barney>
<Fred> <and> <Barney>

So you should always do something like this:

#!/usr/bin/perl
use strict;
use warnings;

my @strings = (
  "FredandBarney",
  "Gilligan or Skipper",
  "Fred and Ginger"
);
foreach my $string (@strings) {
  if( $string =~ m/(\S+)(and|or)(\S+)/ ) {
    print "<$1> <$2> <$3>\n";
  }else{
    print "No match\n";
  }
};

__output__
<Fred> <and> <Barney>
No match
No match

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to