Perl中著名的Schwartzian转换,其产生背景主要涉及到排序问题:
比如说,根据文件名以字母顺序排序,代码如下:
use strict; use warnings; my @files = glob "*.xml"; #perl中文件操作符glob提供相当于shell中的通配符的功能 my @sorted_files = sort @files; #sort(),排序,默认是字母顺序排序
use strict; use warnings; #length求长度。 太空船操作符<=>,默认变量是$a,$b,返回值为-1,0,1分别表示大于,==,小于。 sort进行排序 my $files = ".xml"; my @sorted_length = sort { length($a) <=> length($b) } @files;
use strict; use warnings; my @files = glob "*.xml"; my @sort_size = sort { -s $a <=> -s $b } @files; #比较大小
use strict; use warnings; my @files = glob "*.xml"; my @unsorted_pairs = map { [$_, -s $_] } @files; my @sorted_pairs = sort { $a->[1] <=> $b->[1] } @unsorted_pairs; my @sorted_files = map { $_->[0] } @sorted_pairs;
my @quickly_sorted_files = map { $_->[0] } sort { $a->[1] <=> $b->[1] } map { [$_, -s $_] } @files;
#!/usr/bin/perl -w use strict; use warnings; use autodie; use v5.10; ###################################### ### 创建要比较的10,000个.xml文件 ### ###################################### my $profix = ".xml"; foreach my $num (1..10000) { open(my $fh, '>', $num . $profix) || die "Can not create the file: $!\n"; print $fh "This is file size testing!"; } print "All the 10_1000 files created! \n"; ###################################### ### 常规转换: 遍历20次 ### ###################################### my $t1 = time(); foreach (1..20){ my @files = glob "*.xml"; my @sorted = sort { -s $a <=> -s $b } @files; } say "常规算法需要时间: => ", time()- $t1; ###################################### ### Schwartzian转换: 遍历20次 ### ###################################### my $t2 = time(); foreach (1..20){ my @files = glob "*.xml"; my @sorted = map {$_->[0]} sort {$a->[1] <=> $b->[1]} map {[$_, -s $_]} @files; }say "Schwartzian算法需要时间: => ", time()- $t2;
输出结果:
All the 10_1000 files created!
常规算法需要时间: => 185
Schwartzian算法需要时间: => 115