user3166700
user3166700

Reputation: 25

Matching and counting leading whitespaces in perl

I am fairly new to regexes and i got a little problem with counting (only leading) whitespaces in a string.
Let's say i got a string that looks like this:

my $str="        for getopts :h opt;; do       #this is just a comment";

and now i only want to count the leading spaces / tabs in this string. No changing of the original string - just counting.

I tried something like this (i know that's pretty trivial):

my $count =()= $str =~ /"^[\\t]|^\\s+"/gm;

But unfortunately this counts of course just the first whitespace in this string.
Anybody got an idea ?

Upvotes: 2

Views: 1725

Answers (2)

Borodin
Borodin

Reputation: 126732

It's not clear whether your string is

'my $str="        for getopts :h opt;; do       #this is just a comment";'

or just

'        for getopts :h opt;; do       #this is just a comment'

but I'm assuming the latter. However there aren't any double quotes in that string so your regex will fail because it requires them.

I can't get your statement to do anything useful. Do you realise that \\s and \\t within a regex means the literal characters backslash \ and s or t, and not the metacharacters for whitespace and tab?

An alternative way that you probably won't understand is

my $count = () = $str =~ /\G\s/g;

which works by putting the global match in list context so that all the leading spaces are found one by one, and then putting that list in scalar context to return its length.

However the easiest and most obvious way is to capture all the whitespace at the start of the string, and measure its length, like this

use strict;
use warnings;
use 5.010;

my $str = "        for getopts :h opt;; do       #this is just a comment";

$str =~ /^(\s*)/;
my $count = length($1);

say $count;

output

8

Upvotes: 4

Lee Duhem
Lee Duhem

Reputation: 15121

You could use the following code to find out the count of leading whitespace in $str

if ($str =~ m/^(\s+)/) {
    $count = length $1;
}

Upvotes: 1

Related Questions