根据行号显示文件内容
编写一个 Perl 程序,根据通过命令行参数给出的行号以排序顺序(升序)显示文件的内容。请注意,行号可以按任何顺序排列,如果行号很大,则会引发错误。
Syntax: perl Filename.pl
File_to_be_read.abc
x y z
Here,
Filename.pl is the name of the file that contains the perl script
File_to_be_read.abc is the name of the file which is to be read. This file can be of any type. Ex- text, script, etc.
x y z are the line numbers which are to be printed.
方法:
对不包括第一个参数(文件名)的行号进行排序。排序后,使用单个语句(my @file =
示例 1:考虑一个文件 Hello.txt
#!/usr/bin/perl
use warnings;
use strict;
# Check if line numbers are given as an input
if (@ARGV < 2)
{
die "usage: pick file_name line_no1 line_no2 ...";
}
open FNAME, $ARGV[0] or die "cannot open file";
# Exclude the first argument
# for sorting line numbers
shift (@ARGV);
my @line_numbers = sort { $a <=> $b } @ARGV;
# Read whole file content into an array
# and removes new line using chomp()
chomp (my @file = );
foreach my $var (@line_numbers)
{
if ($var> $#file)
{
print "Line number $var is too large\n";
next;
}
print "$file[$var-1]\n";
}
close FNAME;
输出:
示例 2:读取相同的脚本文件
#!/usr/bin/perl
use warnings;
use strict;
# Check if line numbers are given as an input
if (@ARGV < 2)
{
die "usage: pick file_name line_no1 line_no2 ...";
}
open FNAME, $ARGV[0] or die "cannot open file";
# Exclude the first argument
# for sorting line numbers
shift (@ARGV);
my @line_numbers = sort { $a <=> $b } @ARGV;
# Read whole file content into an array
# and removes new line using chomp()
chomp (my @file = );
foreach my $var (@line_numbers)
{
if ($var> $#file)
{
print "Line number $var is too large\n";
next;
}
print "$file[$var-1]\n";
}
close FNAME;
输出:
如果传递的行号不在文件中:
在评论中写代码?请使用 ide.geeksforgeeks.org,生成链接并在此处分享链接。