On Sun, Apr 10, 2011 at 12:27 AM, Brian F. Yulga
<byu...@langly.dyndns.org> wrote:
> shawn wilson wrote:
>>
>> On Sat, Apr 9, 2011 at 3:29 PM,<sono...@fannullone.us>  wrote:
>>
>>>
>>>> my $address_count = () = $str =~ /box|street|avenue|lane|apo/ig;
>>
>> what does print $var = () = $str =~ /regex/; do?
>> particularly the '= () ='?
>>
>
> According to "Effective Perl Programming (2nd Ed.)", Item 9 (Know the
> difference between lists and arrays)...
> (I couldn't find the text online, so my apologies for poorly paraphrasing
> the book)
> Since the assignment operator is right associative, the '() = ...' happens
> first, which forces the assignment operator to act in list context on the
> regex match on the right.  Then the '$var =' to the left is the assignment
> operator in scalar context, which returns the number of elements from the
> list on the right.
>
> This code can be used to count the number of matches from your regex, if you
> don't care to do anything with the actual matches.
>
> my $count =()= m/(.....)/g;
>
> Apparently this is called the "goatse operator".  no kidding; that's what
> the book says.

that's cool

>>
>> per the question, maybe something like this:
>> my @match = [ qr/one/i, qr/two/i, qr/etc/i ];
>> my @words = split /[^\s]+/, $fields;
>> my $count = 0;
>> foreach my $word (@words) {
>>  $count++ if( $word ~~ @match );
>> }
>> print "cool\n" if $count>= 2;
>>
>>
>
> How does this code work?  For one thing, you have @match = [ ]; which is
> assigning an array reference to an array?  Maybe I'm not understanding
> something...  I tweaked your code to the following, since I had problems
> compiling it as you wrote it:
>

heh, i've got to learn to test my code before posting - i'm ending
looking like an idiot :)
*sigh* this is what i wanted to say:


#!/usr/bin/perl

use warnings;
use strict;

my $fields1 = "a little sentense with one and it will match with two\n";
my $fields2 = "this one will not match\n";

work( $fields1 );
work( $fields2 );

sub work {
   my( $fields ) = @_;

   my @match = ( qr/one/i, qr/two/i, qr/etc/i );
   my @words = split /\W+/, $fields;

   my $count = 0;
   foreach my $word (@words) {
      $count++ if( $word ~~ @match );
   }

   print "String: $fields\n";
   print "matched $count\n" if $count >= 2;
}


now, as i stated earlier, when you do matching like that ( $word ~~
@match ) it only matches the first thing that hits. so, if you change
the later part of that function to:
   my $count = () =  $fields ~~ @match;
   print "$count\n";
it'll print 1 for each string you run through. and as i stated
earlier, if anyone knows how to change this behavior (without
overloading) i'd be interested.

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