[Perl] subroutine
作者: reistlin
来源: http://www.reistlin.com/blog/28
更新时间: 2010.07
版权声明: 原创文章.转载请保留作者信息和原文完整.谢绝任何方式的摘要
1. Print Array - 打印数组
&print_array("数组")
#!/usr/bin/perl -w use strict; use Data::Dumper; # Debug Switch my $debug = 0; sub print_array { my @array = @_; my $index; for ( $index = 0; $index < @array; $index++ ) { print "$array[$index] \n"; } } # 测试 my @test = (1,2,3,4,5,6,7,8,9,0); &print_array(@test);
#!/usr/bin/perl -w use strict; use Data::Dumper; # Debug Switch my $debug = 0; sub print_array { my @array = @_; foreach my $tmp (@array) { print "$tmp \n"; } } # 测试 my @test = (1,2,3,4,5,6,7,8,9,0); &print_array(@test);
2. Print Hash - 打印哈希
&print_hash("哈希")
#!/usr/bin/perl -w use strict; use Data::Dumper; # Debug Switch my $debug = 0; sub print_hash { my %hash = @_; while ( my ($key, $value) = each %hash ) { print "$key => $value\n"; } } # 测试 my %test = (a=>1, b=>2, c=>3); &print_hash(%test);
3. Last Digits - 取字符串后"n"位
&last_digits("字符串", "位数")
#!/usr/bin/perl -w use strict; use Data::Dumper; # Debug Switch my $debug = 0; sub last_digits () { my $string = shift; my $digits = shift; my $length = length($string); if ($length > $digits) { print substr($string, $length - $digits, $digits); } } # 测试 &last_digits("987654321", "3");