On 10 Feb, 2012, at 0:31, Jim Gibson <jimsgib...@gmail.com> wrote:

> 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
yes. It's a very good point.  
I wished to use warnings, but mistook use strict as use warnings.  
I'm going to check what's "use strict " for? 
> 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
Before I used TAB just to make it look good.  didn't realize it's spaces 
sensitive.  
>  "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

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

--
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