Perl 根据行号显示文件内容

Perl 根据行号显示文件内容

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

语法: perl Filename.pl File_to_be_read.abc x y z

这里,

Filename.pl 是包含perl脚本的文件名

File_to_be_read.abc 是要读取的文件名。这个文件可以是任何类型的。例如,文本、脚本等。

x y z 是要打印的行号。

方法:

对行号进行排序,不包括第一个参数,即文件名。一旦排序后,使用单个语句将文件的全部内容读入一个数组(my @file = <FNAME>)。 现在循环阅读排序后的行号,并通过将行号作为索引传给文件数组来显示文件内容,如(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 = <FNAME>);
   
foreach myvar (@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 = <FNAME>);
   
foreach myvar (@line_numbers) 
{
    if (var>#file)
    {
        print "Line number var is too large\n";
        next;
    }
    print "file[$var-1]\n";
}
close FNAME;

输出:

根据行号显示文件内容

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

根据行号显示文件内容

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程