Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

Re: Counting the number of items returned by split without using a named array

by Tanalis (Curate)
on May 03, 2006 at 10:12 UTC ( #547106=note: print w/ replies, xml ) Need Help??


in reply to Counting the number of items returned by split without using a named array

Why not just count the instances of whitespace?

my $str = "this is a test string"; my $cnt = 1; # num tokens = whitespace + 1 ++$cnt while $str =~ /\s+/g; print $cnt, "\n"; # prints 5


Comment on Re: Counting the number of items returned by split without using a named array
Download Code
Replies are listed 'Best First'.
Re^2: Counting the number of items returned by split without using a named array
by blazar (Canon) on May 03, 2006 at 11:07 UTC

    The =()= does work with matches:

    $ perl -lpe '($_=()=/\s+/g)++' foo 1 bar baz 2 foo bar baz 3

    But I would use split, especially with the smart behaviour provided by the default ' ' argument.

      That fails when input has leading or trailing blanks:

      $ perl -lpe '($_=()=/\s+/g)++' ## leading foo bar 3 $ perl -lpe '($_=()=/\s+/g)++' ## trailing foo bar 3 $ perl -lpe '($_=()=/\s+/g)++' ## both foo bar 4 $ _

      It's better to count ocurrences of actual elements (\S+):

      $ perl -wle 'print scalar (()=/\S+/g) for "a b c", " a b c", "a b c ", + " a b c "' 3 3 3 3 $ _

      Anyway I prefer split too, like salva++'s 0e0 solution.

      --
      David Serrano

        I know. My entire point was not to maintain a counter manually a' la

        ++$cnt while $str =~ /\s+/g;

        Well done to point out about \S anyway, since one often forgets about \S, \D and \W.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://547106]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others about the Monastery: (5)
As of 2015-07-30 09:13 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (270 votes), past polls