
Laurent_R
Enthusiast
Sep 25, 2012, 5:24 PM
Post #2 of 5
(806 views)
|
|
Re: [lie soul] calling specific lines from a txt file by running the program + the number of the line i want
[In reply to]
|
Can't Post
|
|
Hi, as a start, add the following lines at the beginning of the script:
use strict; use warnings; (The 'use warning;' line is not really mandatory here, since you have the -w flag, whish has essentially the same effect, but modern practice tends to favor the 'use ...' syntax, rather than the -w flag.) Second, these lines are probably wrong:
$infile = $ARGV[0]; $infile = "n.txt"; as the value of $AGV[0] assigned to $infile is lost when you assign another value to the same $infile variable. Third, you are using $infile to store yet something else in the while loop, the lines of your file, this is bad practice as it is confusing (in fact, I suspect that you don't understand exactly what you are doing here). I would suggest something like this:
#!/usr/bin/perl use strict; use warnings; my $line_number = shift; # first argument is the line to be printed my $infile = shift; # second argument is file name #Open file open IN, "$infile" or die "Cannot read $infile: $!\n"; while (my $inline=<IN>) { print $inline if $inline =~ /$line_number/; # prints the line if the number contained in $line_number is found somewhere in the line } close IN; This is assuming that the line number is found in the line to be printed. If you just want to print line number x of the file, irrespective of its content, change the condition in the while loop as follows:
print $inline if $line_number == $.; # $. contains the line number of the current file There are a couple of other things that could be done better, but at least, this should work.
|