Spooky has asked for the wisdom of the Perl Monks concerning the following question:
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: counting leading white spaces
by ikegami (Patriarch) on Feb 11, 2009 at 19:58 UTC | |
"Counting whitespace" doesn't make much sense. Did you mean "counting whitespace characters"?
Update: Presuming a scalar context,
also works. | [reply] [d/l] [select] |
by jwkrahn (Abbot) on Feb 11, 2009 at 20:20 UTC | |
Or:
| [reply] [d/l] |
by Anonymous Monk on Nov 10, 2015 at 19:53 UTC | |
| [reply] |
|
Re: counting leading white spaces
by ww (Archbishop) on Feb 11, 2009 at 22:39 UTC | |
"\s is a whitespace character and represents Hence, I suspect that if the data OP is dealing with has embedded tab chars, the count will be unreliable. FTR, brian d. foy's remarks in perlfaq4.pod either ignore this case or indicate there's something wrong with my understanding (in which case, correction would be welcome). So, in the spirit of self-education, I tried this little experiment (Update: all tabs in original are hard tabs; here they are replaced by multiple spaces</update>): Which largely undermines my supposition above. Update 20090212 00:35 Ignore the comment in line 37. That's not a Perl issue (nor a reflection of my inability to count, but it's waaaaay OT and way complicated). But having elaborated the code in this manner (still using the same array):
the output of that snippet confounds me:
because -- while substituting "_" (only) for \s I now find pipes in the output where \t existed in @var. WTF???? More in the next node below, but it does NOT explain the pipes. :-( | [reply] [d/l] [select] |
by ww (Archbishop) on Feb 12, 2009 at 05:34 UTC | |
| [reply] [d/l] |
|
Re: counting leading white spaces
by hbm (Hermit) on Feb 11, 2009 at 20:08 UTC | |
Or count and delete:
| [reply] [d/l] [select] |
by almut (Canon) on Feb 11, 2009 at 20:29 UTC | |
A problem with tr/// could be that it would count all occurrences, not only leading ones... | [reply] [d/l] |
by hbm (Hermit) on Feb 12, 2009 at 04:05 UTC | |
Good point; bad oversight on my part. Below, I take extra effort to count only leading spaces...
See also JAPH at the firing range | [reply] [d/l] |
|
Re: counting leading white spaces
by Anonymous Monk on Nov 09, 2015 at 07:41 UTC | |
| [reply] [d/l] |
|
Re: counting leading white spaces
by Daga (Initiate) on Apr 27, 2011 at 09:34 UTC | |
Hi you can use below method for the same
| [reply] [d/l] |
by Corion (Patriarch) on Apr 27, 2011 at 09:46 UTC | |
Your code has an error. It reports the wrong number of leading tabs if there are some characters in the line that you didn't cater for:
It's better to avoid split and then checking whether a line contains a certain set of characters, and instead just count the number of tab characters at the start:
| [reply] [d/l] [select] |
|
Re: counting leading white spaces
by Anonymous Monk on Apr 27, 2011 at 09:33 UTC | |
Hi you can use below method for the same
| [reply] [d/l] |