Thanks, that seems is the correct way. However I get those warnings
which I have mentioned and I have to add the weird condition not to
receive warning:
/^(\s+)/;
$i=defined ($1) ? length($1) : 0;
If I write:
/^(\s+)/;
$i=length($1);
I get "Use of uninitialized value in length..."
That's why I put the regex-match in an if-statement, if it doesn't
match, 'number of whitespaces first' are considered zero, or whatever
you are trying to achieve.
I would not trust $n values unless matched in the regex. If you later
loop through several lines you want to count for starting spaces, you
will get last line's value if current line has no starting spaces,
unless you deliberately set a counter to 0, or use an if-statement.
If things aren't working correctly with 'use warnings;' and 'use
strict;', it is because something is programmed wrong...
Your way is one way to make a printable output when $1 is not set
(un-initialized).
Another way:
# Untested!
use strict;
use warnings;
my $string = ' string with whitespaces first';
my $start_space_counter = 0;
if($string =~ /^(\s+)/) {
$start_space_counter = length($1);
}
print "Number of whitespaces first: $start_space_counter\n";
Yet Another way:
# Untested!
use strict;
use warnings;
my $string = ' string with whitespaces first';
if($string =~ /^(\s+)/) {
print 'Number of whitespaces first:', length($1), "\n";
}
else
{
print "No whitespaces first\n";
}
It is up to you to decide what to achieve!