Perl输出带颜色行号或普通输出行
定义好了一个可以输出带颜色行号以及行数据的函数print_with_line_num,f()是测试函数。在f()函数中,读取文件并输出读取的每一行数据,但根据参数选项决定是普通输出行还是同时输出带颜色行号的行数据。
这可以当作是偏函数、闭包、作用域的一个用法示例。
脚本内容如下:
#!/usr/bin/perl -w
use strict;
use 5.010;
# print string with colored line_num
# arg1: line num
# arg2: string to print
sub print_with_line_num {
eval 'use Term::ANSIColor';
my $line_num = shift;
my $string = shift;
my $color = 'bold yellow';
print colored($line_num, $color), ":", "$string";
}
# test function
# arg1: filename for read and print
# arg2: a bool to control whether print line num
sub f {
my $filename = shift;
# arg: print_line_num or not?(bool)
my $print_line_num = shift;
# initialize line_num
my $line_num = 1;
# define a printer, according to the bool of print_line_num,
# choose how to print string
my $myprinter;
{
if($print_line_num){
# print line num
# specify the arg1 to line_num
$myprinter = sub { print_with_line_num "$line_num", @_; }
} else {
# don't print line num,
# so make a simple wrapper for builtin print function
$myprinter = sub { print @_; };
}
}
open my $fh, "$filename" or die "open failed: $!";
while(<$fh>){
$myprinter->($_);
$line_num++;
}
}
if ($ARGV[0] eq "-n"){
f($ARGV[1], 1); # print every line with colored line num
} else {
f($ARGV[0]); # print every line normally
}
下面是测试效果:
普通输出/etc/hosts文件行:
输出带颜色行号的/etc/hosts文件行:
Linux系列文章:https://www.cnblogs.com/f-ck-need-u/p/7048359.html
Shell系列文章:https://www.cnblogs.com/f-ck-need-u/p/7048359.html
网站架构系列文章:http://www.cnblogs.com/f-ck-need-u/p/7576137.html
MySQL/MariaDB系列文章:https://www.cnblogs.com/f-ck-need-u/p/7586194.html
Perl系列:https://www.cnblogs.com/f-ck-need-u/p/9512185.html
Go系列:https://www.cnblogs.com/f-ck-need-u/p/9832538.html
Python系列:https://www.cnblogs.com/f-ck-need-u/p/9832640.html
Ruby系列:https://www.cnblogs.com/f-ck-need-u/p/10805545.html
操作系统系列:https://www.cnblogs.com/f-ck-need-u/p/10481466.html
精通awk系列:https://www.cnblogs.com/f-ck-need-u/p/12688355.html