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.

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:

my $match = [ qr/one/i, qr/two/i, qr/etc/i ];
my @words = split /\s/, $fields;
my $count = 0;
foreach my $word (@words) {
    foreach (@$match) {
        if ( $word =~ $_ ) {
            $count++;
            last;
        }
    }
}
print "cool\n" if $count >= 2;

It's certainly not as short as your code. Is this basically the same logic you were going for?

Here's a slightly different take.... I thought a 'map' or 'grep' might be a cleaner way to go.

my @mail_types = qw( avenue road box lane );
my @words = split /\s/, $fields;
my $count = grep {
    my $found;
    foreach my $street ( @mail_types ) {
        if ( /\b$street\b/i ) {
            $found++;
            last;
        }
    }
    $found;
} @words;
print qq(found $count address types\n) if ( $count > 1);


I think I was wrong; this is even longer, and too convoluted.... I'm sure there's a better way...

Brian

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