in reply to Counting words

There are 2 errors in your code: a syntax error '$pattern = \b\w+\b;' and a logical one. Try this:

my ($count,$pattern,$file) = ( 0 , qr{\b\w+\b} , shift ); # declares and initializes the three variables # see perlop for qr// open FILE,$input or die "Error: $!"; # please read `perldoc -q 'quoting.*vars'` while(<FILE>){ $count += () = /$pattern/g; # that's kind of an idiom for counting the matches # it forces list context on m//g, but forces scalar # context on the resulting empty(?) list # that returns the number of elements that were # assigned to the list, although # in the end it's all thrown away, never reaching any # accessible memory outside the perl-internals... # -- it counts the number of matches } close FILE;

HTH

UPDATE: yes, qr// instead of qx//, i mixed 'em up, because i don't often use qr//. Thanks to sauoq and wog

--
http://fruiture.de

Replies are listed 'Best First'.
Re: Re: Counting words
by PodMaster (Abbot) on Aug 24, 2002 at 11:48 UTC
     $count += () ... kind of an idiom

    I've always hated that idiom. It's so satanic.

    #!/usr/bin/perl use strict; use warnings; my $COUNT = 0; while(<DATA>){ $COUNT++ while m{\b\w+\b}g; } die "COUNT $COUNT"; __END__ Hello there boss! How are you doing today. I really hope you don't slip on that banana peel. I count 22 words.

    ____________________________________________________
    ** The Third rule of perl club is a statement of fact: pod is sexy.

Re: Re: Counting words
by wog (Curate) on Aug 24, 2002 at 05:27 UTC

    I think fruiture meant to write qr instead of qx. ("Quote Regex" as opposed to "Quote eXecute". Of course checking perlop, as reccommended, would hopefully let one fiquire this out...)