How can I report line number in Perl?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Greg M

    How can I report line number in Perl?

    I'm not sure how to phrase the question so I'll just show what I'm trying to do.

    I have somewhere in a file:

    abcdefg1abcdefg
    abcdefg abcdefg
    abcdefg abcdefg

    I used regex to locate where the "1" is, now I want it to print out aaabbbcccdddeee fffggg1aaabbbcc c...

    I made the entire document into an array and I could get it to work if I knew the line number where the 1 is located. But I can't seem to figure that out. Help?
  • numberwhun
    Recognized Expert Moderator Specialist
    • May 2007
    • 3467

    #2
    My suggestion would be to create a counter that increments as each line is read. When the object is found, report the line number that the counter is at.

    Regards,

    Jeff

    Comment

    • RonB
      Recognized Expert Contributor
      • Jun 2009
      • 589

      #3
      No need to increment a counter.

      If you have the entire file in an array, which is rarely the best/proper approach, the line number will be 1 greater than the array index where the "1" is found.

      If you're looping over the file contents line-by-line, then Perl automatically keeps track of the line number in its built-in $. var.

      Comment

      Working...