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

Hi, I am reading through a text file and when I encounter a specific text, I need to report it in the screen along with the line number in which it is appearing. I say print $.. Is there a similar way with which I can display the column number of the instance? For example, I want to report the column and line number in which character '&' is appearing. The message has to be

Line xx Col xx: & found.

print "Line $. : & found\n";

prints the line number, similarly I need to print the column number too. Any suggestions?

Replies are listed 'Best First'.
Re: Displaying the column number when reading a file
by Hue-Bond (Priest) on Aug 07, 2006 at 13:01 UTC

    Use index:

    my $str = 'this is some text'; print index $str, 'o'; __END__ 9

    --
    David Serrano

Re: Displaying the column number when reading a file
by bart (Canon) on Aug 07, 2006 at 13:06 UTC
    The column number is just the offset of the substring in the current line. You tend to have the whole line in memory. Use whatever means to fetch that position from the string.

    For example: the array @-, or pos (you need to use /g on the regexp for the latter to work)

    /&/ and printf "Line %d Col %d: & found.\n", $., $-[0]+1;
Re: Displaying the column number when reading a file
by gellyfish (Monsignor) on Aug 07, 2006 at 13:02 UTC

    If you are using a regular expression to find the character you could use len($`) + 1, or you could use index

    /J\

Re: Displaying the column number when reading a file
by Velaki (Chaplain) on Aug 07, 2006 at 13:04 UTC

    As a variant to index, perhaps using pos would work, and then you could offset the find by the length of the thing you're looking for.

    #!/usr/bin/perl use strict; use warnings; while (<DATA>) { my $search = 'foo'; if (/foo/g) { print "Line $. Col ", pos() - length($search), ": $search found.\n"; } } __DATA__ This is a test. This is foo. foo is good. # Results #Line 2 Col 8: foo found. #Line 3 Col 0: foo found.

    Hope this helped,
    -v.

    "Perl. There is no substitute."
Re: Displaying the column number when reading a file
by ww (Archbishop) on Aug 07, 2006 at 20:36 UTC
    ++ the above, but a stray concern intrudes: what if OP is talking about "column number" in the sense widely used by folk looking at
    xxx yyyyy zzzz 111 aaa bbbb ccccc 222
    who declare, not without justification, that the "y"s and "b"s appear in column two; the numerals "1" in column 4 and the numbers "2" in column 5.

    rsriram... this is a case where more precise language, or a sample of the dataset would help.

    and, if this is indeed a comma or tab delimited text file, why ...count the tabs!