Perl中著名的Schwartzian转换问题解决实现
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; #比较大小
上面的代码设计到三重(次)操作:
1. 从硬盘上获取文件大小(-s $b)
2. 比较文件大小(太空船操作)
3. 对其进行排序(sort操作)
考虑到要比较$a,$b大小时,要从硬盘中获取两次,所以次数是6次!也就是说,如果有1万个文件,总共是6万次。
其算法复杂度是: n*long(n),考虑到后两项(比较文件大小,进行排序)必然要进行的操作,但第一项却可以降低!
即一次性从硬盘中读取所有文件大小,将其放置到Perl中的默认的变量,并存储到内存中!于是又下面算法实现:
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;
看上去比较复杂,分三个步骤解释下:
第一步:遍历文件列表,对每个文件创建一个数组引用。数组引用包含两个元素:
第一个是文件名($_),第二个是文件大小(-s $_)。这样,处理每个文件只访问一次磁盘。
第二步:对二维数组排序。因比较文件大小,所以需取元素[1],比较它们的值。得到另一个二维数组。
第三步:丢掉文件大小元素,创建一个只含文件名的列表。完成目标!
上面的代码使用了两个临时数组,但这并不是必须的。我们可以一个语句就能完成所有的工作。为了达到目的,需要按照“数据从右流向左”的原理反转句子顺序,不如果将每个句子放在单独一行,并且留出足够的空间,我们依然可以写出可读性高的代码。
my @quickly_sorted_files =
map { $_->[0] }
sort { $a->[1] $b->[1] }
map { [$_, -s $_] }
@files;
这就是以Randal L. Schwartz命名的Schwartzian转换,对数据量特多的情况下,其速度要比前者快数倍!
下面写了小程序,包括在生成1万个xml文件,在两种情况下,完整代码如下:
#!/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

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Use Vue.js and Perl languages to develop efficient web crawlers and data scraping tools. In recent years, with the rapid development of the Internet and the increasing importance of data, the demand for web crawlers and data scraping tools has also increased. In this context, it is a good choice to combine Vue.js and Perl language to develop efficient web crawlers and data scraping tools. This article will introduce how to develop such a tool using Vue.js and Perl language, and attach corresponding code examples. 1. Introduction to Vue.js and Perl language

In today's digital age, web applications are becoming more and more common, making our lives more convenient and efficient. Python and Perl are two widely used programming languages, both of which are ideal for building web applications. However, to build high-performance web applications, you need to master some best practices. This article will introduce some best practices for building high-performance web applications in Python and Perl. Choosing the right web framework Choosing a suitable web framework is a critical step in designing high-performance web applications.

Using Vue.js and Perl language to develop system scripts and automation tools In the current software development environment, system scripts and automation tools have become important tools for developers to save time and improve efficiency. In this article, we will introduce how to develop system scripts and automation tools using Vue.js and Perl language, and provide some code examples. Vue.js is a popular JavaScript framework for building user interfaces. It adopts a component-based development approach, allowing developers to

Building perl+fastcgi+nginx nginx+fastcgi is the most popular environment under PHP. Will perl also have fastcgi? Of course it does. Today, let’s build perl’s fastcgi under nginx. The performance is no less than that of PHP. But now the popularity of the web program PHP is unmatched by perl. No matter how good the performance is, it is in vain. However, some small functions can be solved by using perl's fastcgi. Let's get to the point. 1. Prepare the software environment: nginxperl: The system comes with fastcgi1.2perl installation Generally, Linux comes with perl, so you don’t need to install it. If it doesn’t, please execute:

Redis and Perl language development: building efficient command line tools Introduction: Redis is an open source in-memory data storage system written in C language. It has high performance and flexible features and is widely used in scenarios such as caching, message queues and real-time analysis. . Perl is a scripting language with powerful text processing and regular expression capabilities, making it ideal for rapid development of command-line tools. This article will introduce how to use Perl language and Redis to build efficient command line tools, and provide relevant code examples. one

How to use Redis and Perl to develop recommendation system functions Recommendation system is a very important part of modern Internet applications, which can help users discover content or products that may be of interest to them. In this article, we will introduce how to develop a simple recommendation system function using Redis and Perl, and provide specific code examples. First, let's understand the basic concepts of Redis and Perl. Redis is an open source in-memory data storage system that can be used as a database, cache, and messaging middleware. it

How to use Redis and Perl to develop a simple key-value storage function Introduction: Redis is an open source in-memory data structure storage system that can be used to store and access data efficiently. Perl is an advanced scripting programming language with rich text processing capabilities and convenient module integration. This article will introduce how to use Redis and Perl to develop simple key-value storage functions, and provide specific code examples. 1. Install Redis and Perl modules. First, you need to install Red on the server.

Multilingual conversion issues in text translation, requiring specific code examples With the further development of globalization, text translation has become more and more important in daily life and business communication. When translating text, we often face the problem of multi-language conversion. This article will discuss the issue of multilingual conversion and provide some specific code examples to help readers better understand and apply it. The multilingual conversion problem mainly involves converting a piece of text from one language to another. In practical applications, we often need to convert a piece of English text into Chinese, French, Spanish
