糯米

TI DaVinci, gstreamer, ffmpeg
随笔 - 167, 文章 - 0, 评论 - 47, 引用 - 0
数据加载中……

perl 常用函数


摘自 perldoc.perl.org

map BLOCK LIST
map EXPR, LIST
对于 LIST 里的每一个元素按照 BLOCK 或者 EXPR 里的操作进行求值。
返回求值结果组成的数组。
如果返回值是 scalar 类型,则返回结果数组的大小。
例子:
返回一组数字对应的字符
@chars = map(chr, @numbers);
返回一组数字的平方
my @squares = map { $_ > 5 ? ($_ * $_) : () } @numbers;
返回大于5的数字的平方
my @squares = map { $_ > 5 ? ($_ * $_) : () } @numbers;
由于 map 总是返回一个列表,因此可以赋值给哈希类型的变量:
%hash = map { get_a_key_for($_) => $_ } @array;
也可以这样写:
%hash = ();
foreach (@array) {
    $hash{get_a_key_for($_)} = $_;
}

-X FILEHANDLE
文件测试函数:
-r  File is readable by effective uid/gid.
-w  File is writable by effective uid/gid.
-x  File is executable by effective uid/gid.
-o  File is owned by effective uid.
-R  File is readable by real uid/gid.
-W  File is writable by real uid/gid.
-X  File is executable by real uid/gid.
-O  File is owned by real uid.
-e  File exists.
-z  File has zero size (is empty).
-s  File has nonzero size (returns size in bytes).
-f  File is a plain file.
-d  File is a directory.
-l  File is a symbolic link.
-p  File is a named pipe (FIFO), or Filehandle is a pipe.
-S  File is a socket.
-b  File is a block special file.
-c  File is a character special file.
-t  Filehandle is opened to a tty.
-u  File has setuid bit set.
-g  File has setgid bit set.
-k  File has sticky bit set.
-T  File is an ASCII text file (heuristic guess).
-B  File is a "binary" file (opposite of -T).
-M  Script start time minus file modification time, in days.
-A  Same for access time.
-C  Same for inode change time (Unix, may differ for other platforms)

delete EXPR
EXPR 为哈希变量的 slice 或者是单个元素。
返回值为删除掉元素的值,可以是列表。
如果返回值被要求为 scalar 类型,则返回被删除的最后一个值。
delete 也可以用于数组类型的变量,不过它的行为可能不是你所预想的那样。
例子:
%hash = (foo => 11, bar => 22, baz => 33);
$scalar = delete $hash{foo};             # $scalar is 11
$scalar = delete @hash{qw(foo bar)};     # $scalar is 22
@array  = delete @hash{qw(foo bar baz)}; # @array  is (undef,undef,33)

each HASH
each ARRAY
each EXPR
返回哈希的每个 (key, value) 所组成的数组。
例子:
while (($key, $value) = each %hash) {
    print $key, "\n";
    delete $hash{$key};   # This is safe
}

eof FILEHANDLE
eof ()
eof
注意 eof() 与 eof 的区别:
eof():如果到达了 <> 的最后一个文件的末尾,则返回1
eof:如果到达了当前文件的末尾,则返回1
# reset line numbering on each input file
while (<>) {
    next if /^\s*#/;  # skip comments
    print "$.\t$_";
} continue {
    close ARGV if eof;  # Not eof()!
}
# insert dashes just before last line of last file
while (<>) {
    if (eof()) {  # check for end of last file
        print "--------------\n";
    }
    print;
    last if eof();          # needed if we're reading from a terminal
}


posted on 2011-08-26 18:25 糯米 阅读(433) 评论(0)  编辑 收藏 引用 所属分类: Perl


只有注册用户登录后才能发表评论。
【推荐】超50万行VC++源码: 大型组态工控、电力仿真CAD与GIS源码库
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理