Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

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

by Hue-Bond (Priest)
on May 03, 2006 at 13:38 UTC ( [id://547150]=note: print w/replies, xml ) Need Help??


in reply to Re^2: Counting the number of items returned by split without using a named array
in thread Counting the number of items returned by split without using a named array

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

Replies are listed 'Best First'.
Re^4: Counting the number of items returned by split without using a named array
by blazar (Canon) on May 03, 2006 at 13:47 UTC

    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
Domain Nodelet?
Node Status?
node history
Node Type: note [id://547150]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (3)
As of 2024-03-28 15:44 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found