hifirock has asked for the wisdom of the Perl Monks concerning the following question:

Hi, How can i find the starting character position in a line.
ex:
$line = " This is the test line";

from the above line i need to find out the position of the starting character (in this case its 'T').
Line may contain any tab or spaces at the beginning of the line. can anyone pls help me.
  • Comment on find the starting character position in a line

Replies are listed 'Best First'.
Re: find the starting character position in a line
by Corion (Patriarch) on Apr 16, 2009 at 07:01 UTC

    I recommend reviewing your course notes. You can approach the problem using index, Regular Expressions, or with the following code:

    $line = " This is the test line"; $* = 'line'; # prepare Perl for treating 'line' @${*} = grep { !m!\s! } split //, reverse (''.$${*}); shift @{$*} while @{$*} > $[ +1; print $line[-1], " is the first character.\n";
Re: find the starting character position in a line
by linuxer (Curate) on Apr 16, 2009 at 08:47 UTC
    $ perl -wle ' $line = " This is a test."; if ( $line =~ m/(\S)/g ) { print pos($line); } ' 4
Re: find the starting character position in a line
by dHarry (Abbot) on Apr 16, 2009 at 07:03 UTC
Re: find the starting character position in a line
by wol (Hermit) on Apr 16, 2009 at 10:23 UTC
    The position of the first non-space character is the same as the number of (space) characters preceding it. So:
    $line =~ m/^(\s*)/; print length $1;
    or if you're allergic to line endings:
    print length [$line =~ m/^(\s*)/]->[0];

    --
    use JAPH;
    print JAPH::asString();

Re: find the starting character position in a line
by Anonymous Monk on Apr 16, 2009 at 07:05 UTC
    What do you plan on doing with that information?

    $line = " This is the test line"; if( $line =~ /(\S)/ ){ # match first non-space character print index($line, $1),"\n"; # find index } __END__
    perldoc -f index
Re: find the starting character position in a line
by jwkrahn (Abbot) on Apr 16, 2009 at 15:06 UTC
    $ perl -le' my $line = " This is the test line"; $line =~ /^\s+/ and print $+[ 0 ]; ' 1