定義好了一個能夠輸出帶顏色行號以及行數據的函數print_with_line_num,f()是測試函數。在f()函數中,讀取文件並輸出讀取的每一行數據,但根據參數選項決定是普通輸出行仍是同時輸出帶顏色行號的行數據。閉包
這能夠看成是偏函數、閉包、做用域的一個用法示例。app
腳本內容以下:函數
#!/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文件行:ui
輸出帶顏色行號的/etc/hosts文件行:code