in reply to Help with regex

Why do you think you are doing something wrong? Please provide a small sample of your input file, the corresponding output, and what you expect the output to be.

When I run your code with my own input, the output I get is the line number plus 1 of the lines which just contain 1\n. To get the actual line number:

$linenumber=1; foreach $line(@fileData) { if ($line =~ m/^1$/) { print "$linenumber\n"; } $linenumber++; }
Update: You could also use the special variable $. instead of $linenumber

tinita is more precise. $. is used with filehandles.

Replies are listed 'Best First'.
Re^2: Help with regex
by tinita (Parson) on Sep 28, 2007 at 16:48 UTC
    You could also use the special variable $. instead of $linenumber.
    not while looping over an array, only when reading lines from a filehandle.
Re^2: Help with regex
by mr_mischief (Monsignor) on Sep 28, 2007 at 17:45 UTC
    Some say premature optimization is the root of all programming evils (but then they must not have ever used COBOL). Overly concise code is generally a bad idea in production, too. However, I think that without hurting clarity it's always better to remove code to fix a problem rather than moving it around. This can often be done simply for off-by-one errors.
    foreach $line ( @fileData ) { $linenumber++; if ( $line =~ m/^1$/) { print "$linenumber\n"; } }
    Then there's the issue of idiomatic usage, which may or may not lead one to use $_, implicit matching against $_, or 'for' instead of 'foreach', depending one their views. This leads to code about as legible as the previous for many Perl coders, but I think it's fair to call it a matter of preference.
    for ( @fileData ) { $linenumber++; if ( m/^1$/ ) { print "$linenumber\n"; } }
    Which shouldn't be confused at all with golf, which does hinder legibility somewhat.
    $l++,/^1$/&&print$l.$/for@f;