天天看点

perl脚本练习

题目: 

12 34 56 78  

24 65 87 90  

76 11 67 87  

100 89 78 99 

求出文本中数字的最大、小值 

我看很多的朋友都用shell的awk实现了,但本人对awk不是很了解,试着用perl简单的写了一下,也能实现

code:

#!/usr/bin/perl -w 

use strict; 

use List::Util qw(max min); 

open my $file,'<','e.txt' or die "$!\n"; 

my @array = map {split /\s+/} <$file>; 

close $file; 

print min(@array),"\n"; 

print max(@array),"\n";

第8行代码的也可以这样省略写

my @array = map {split} <$file>; 

或者这样写

my @array = map split,<$file>; 

抓图看一下:

<a target="_blank" href="http://blog.51cto.com/attachment/201104/172801979.png"></a>

output:

<a href="http://blog.51cto.com/attachment/201104/174027838.png" target="_blank"></a>

第二种方法:

my @array = (); 

open FILE,'&lt;','e.txt' or die "$!\n"; 

while (&lt;FILE&gt;) { 

       chomp; 

       push @array,split; 

close FILE; 

@array = sort {$a&lt;=&gt;$b} @array; 

print "Min:\n"; 

print "\t$array[0]\n"; 

print "Max:\n"; 

print "\t$array[$#array]\n"; 

图示

<a href="http://blog.51cto.com/attachment/201104/143301630.png" target="_blank"></a>

本文转自dongfang_09859 51CTO博客,原文链接:http://blog.51cto.com/hellosa/535076,如需转载请自行联系原作者