perl基础
color]【localtime】my ($mday,$mon,$wday) = (localtime(time() - 86400 ));
localtime基本格式:
($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) =
localtime(time);
【Perl中的URL编码和解码】
文章分类:JavaEye
今天我在项目上遇到一个问题,我要用写一个shell script去拷贝pdf文件,因为项目的需要,我要在原来文件名的后面加上一个子标题,然后问题出现在这个子标题上,因为我们知道文件名中是不可以有 \ / : * ? " < > 这些符号的.而我们的子标题中恰好有这些特殊字符.
如何过滤掉这些特殊字符呢?有一个办法就是利用URL编码的原理,将特殊字符转换成百分号的形式就可以了.
我们知道在java中,我们可以通过java.net.URLEncoder.encode()给一个URL编码,然后通过java.net.URLDecode.decode()解码.在javascript中也有类似功能的方法,escape()用于编码,unescape()用于解码.在shell中是没有这么强大的内置函数了,
相比之下用Perl来实现要简单的多,我可以在shell中调用perl的方法来实现encode的功能,代码如下:
<code>
#!/opt/perl-5.6.1/bin/perl
# -------------------------------------
# Encode url
# Jssay Jiang
# -------------------------------------
use strict;
my ($url) = @ARGV;
$url =~ s/([^A-Za-z0-9])/sprintf("%%%02X", ord($1))/seg;
print "$url";
#$url =~ s/\%({2})/pack('C', hex($1))/seg;
#print "$url";
exit 0;
</code>
PS:注释部分为解码方法.
Refer to http://www.jssay.com/blog/index.php/2009/10/20/perl%e7%9a%84url%e7%bc%96%e7%a0%81%e5%92%8c%e8%a7%a3%e7%a0%81/
【Grep】
In Perl:
#!/usr/bin/perl
my $string = ‘fin_helm’;
my @array = qw/full_plate manteau boots two_handed_sword fin_helm/;
if(grep $_ eq $string, @array)
{
print “$string is in the array”;
}
So, those codes do exactly the same.
If you don’t know much perl you will be wondering what does the grep function, the grep function examines each of an element of an array (represented with $_) and then we make a comparison or something with it, in this case $_ eq $string, grep, returns the elements with where true, in this case we are not requesting the elements, we are requesting a sacalar value, so, in perl 0 is false, and every other number is true, that will return 1, so its true, and the element is in the array
I hope you all find this useful, bye
工作中碰到的一个例子:
if (grep {$_ eq encode("utf8",$in)} @allword) {
print $replace,"\n";
}
页:
[1]