Perl语言擅长做文本处理,文本其实就是程序中的字符串,一下是关于perl处理字符串的总结.
【注意事项】
1、if(<STDIN>)时,在终端输入,数据不会自动存储在$_中;while(<STDIN>)时,在终端输入,数据会自动存储在$_中。
【perl查看字符串ASCII值】
#! /usr/bin/perl -w
#
my $str;
print "$#ARGV,$ARGV[0]\n";
if($#ARGV eq 0){
while(<>)
{
$str .= $_;
}
print $str;
}else{
print "input string\n";
$str = <STDIN>;
}
print "input char_index\n";
while(<>){
if($_>0){
$ch = substr $str, ($_-1),1;
$num = ord($ch);
print "OUT:[$ch =>$num]\n";
}else{
print "index must>0.\n";
}
}
【杀死vs进程】
#! /usr/bin/perl -w
#
my $str = `ps -e | grep vs.*`;
#print $str;
my @a;
while($str =~ m/([0-9]{4,})\b/g){
push @a,$1;
}
print "all:\n@a\n";
foreach(@a){
system "kill -9 $_";
}
【查找指定目录下的所有文件和目录及总大小】
#
# File: lsr_s.pl
# Author: 路小佳
# License: GPL-2
use strict;
use warnings;
sub lsr_s($) {
my $cwd =shift;
my @dirs= ($cwd.'/');
my ($dir,$file);
while($dir = pop(@dirs)) {
local*DH;
if(!opendir(DH, $dir)) {
warn "Cannot opendir $dir: $! $^E";
next;
}
foreach (readdir(DH)) {
if ($_ eq '.' || $_ eq '..') {
next;
}
$file = $dir.$_;
if (!-l $file && -d _) {
$file .= '/';
push(@dirs, $file);
}
process($file, $dir);
}
closedir(DH);
}
}
my ($size, $dircnt, $filecnt) = (0, 0, 0);
sub process($$) {
my $file= shift;
print$file, "\n";
if(substr($file, length($file)-1, 1) eq '/') {
$dircnt++;
}
else {
$filecnt++;
$size+= -s $file;
}
}
lsr_s('.');
print "$filecnt files, $dircnt directory.$size bytes.\n";
【命令行参数关键字】
@ARGV 是你的命令行输入参数数组
$#ARGV 是你的参数个数
$ARGV 是你用<>读取文件时,当前的那个文件名称