📜  根据行号显示文件内容

📅  最后修改于: 2022-05-13 01:55:18.251000             🧑  作者: Mango

根据行号显示文件内容

编写一个 Perl 程序,根据通过命令行参数给出的行号以排序顺序(升序)显示文件的内容。请注意,行号可以按任何顺序排列,如果行号很大,则会引发错误。

方法:
对不包括第一个参数(文件名)的行号进行排序。排序后,使用单个语句(my @file = )将文件的全部内容读入数组。现在遍历排序的行号并通过将行号作为索引传递给文件数组来显示文件内容,例如 ( print "$file[$var-1]\n"; )。

示例 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;

输出:

如果传递的行号不在文件中: