For Programmers: Free Programming Magazines  


Home > Archive > PERL Beginners > January 2006 > Simple question on printing a range of lines from a file









You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

 

Author Simple question on printing a range of lines from a file
czimmer@wczimmerman.dyndns.org

2006-01-10, 4:02 am

I need to search for a string in a large text file and print from the
matching line + the 50 lines afterwards. I'm getting an "Use of
uninitialized value at line 9" but I cannot figure out why. I know
that my $begin and $end variables are working as I ran the script with
print statements to verify them. What am I missing?

#!/usr/bin/perl -w
use strict;
open(OUTPUT,"output") || die "Cannot open! \n";
while (my$line = <OUTPUT> )
{
if ($line =~ /String to search for/) {
my$begin = $.;
my$end=($begin + 50);
print if $begin .. $end;
}
}
close (OUTPUT);

Brad Baxter

2006-01-10, 4:02 am

czimmer@wczimmerman.dyndns.org wrote:
> I need to search for a string in a large text file and print from the
> matching line + the 50 lines afterwards. I'm getting an "Use of
> uninitialized value at line 9" but I cannot figure out why. I know
> that my $begin and $end variables are working as I ran the script with
> print statements to verify them. What am I missing?
>
> #!/usr/bin/perl -w
> use strict;
> open(OUTPUT,"output") || die "Cannot open! \n";
> while (my$line = <OUTPUT> )
> {
> if ($line =~ /String to search for/) {
> my$begin = $.;
> my$end=($begin + 50);
> print if $begin .. $end;
> }
> }
> close (OUTPUT);


You are printing $_ (which is uninitialized) instead of $line.
Your logic is flawed, too, I'm afraid; it won't do what you want,
because you only print when $line matches.

perl -ne'($l=$.+50,$f++)if/String to search for/;$f..$.<=$l&&print'
output

But that might give you unexpected results if the string to search
for appears on one of the 50 lines.

--
Brad

Sponsored Links







Also available: Server administration forum archive | Web Design forum archive | Software forum archive | Hardware reviews archive

Copyright 2009 codecomments.com