Perl-->文件的操作
创始人
2024-02-22 08:54:28

1,从一个文件的完全路径中找出它的文件名

#!/usr/bin/perl -w

use File::Basename;
$path = "/home/sysadmin/test/aaa.txt.html";
$basename = basename($path, ".html");
print $basename . "\n";


我们只需要把文件的完全路径,还有要剔除的扩展名传给它,如果没有第二个参数,就取出完整文件名。



2,对目录进行递归搜索


#!/usr/bin/perl -w

use File::Find;

$path = '/home/sysadmin/test';

find(\&handleFind, $path);

sub handleFind {
    my $foundFile = $File::Find::name;
    print "$foundFile\n" if ($foundFile =~ /\.html?$/i);
}




3,一次读入整个文件内容。


#!/usr/bin/perl -w

$path = '/home/sysadmin/test/aaa.txt.html';
open FH, "< $path";
$/ = undef;
$slurp = ;
print $slurp;


打开文件的另外一种方法:


#!/usr/bin/perl

use warnings;

$file = '/etc/passwd';

open PASSWD, "< $file"
 or die "How did you get logged in? ($!)";

while(){
     print $_;
}



4,删除某个目录下的特征文件


#!/usr/bin/perl -w

use File::Find;

$path = '/home/sysadmin/test';

find(\&wanted, $path);

sub wanted {  
      if (-f $File::Find::name)  
             {  
               if ($File::Find::name=~/\.cvs$/i or $File::Find::name=~/\.jpg$/i)
                   {  
                      print "Removing $File::Find::name\n";  
                             unlink   $File::Find::name;  
                    }  
              }  
}




5,复制文件或者目录


#!/usr/bin/perl

use warnings;

use File::Copy;

$source = '/etc/passwd';
$target = '/usr/local/src';
 
copy( "$source", "$target" ) or die "Copy failed: $!";


另外一种方法:

#!/usr/bin/perl

use warnings;

$source = "/home/jive/";
$target = "/usr/local/src";

system("cp -rdp $source $target");



5,移动文件


#!/usr/bin/perl

use warnings;

use File::Copy;

$source = '/home/sysadmin/lvs';
$target = '/usr/local/src';

move( "$source", "$target" ) or die "Copy failed: $!";



6,找出指定目录下的文件和目录


$dir = "/home/sysadmin/aa";

opendir(DIR,"$dir") or die "Can't open the current directory: $!\n";

@names = readdir(DIR) or die "Unable to read current dir:$!\n";

closedir(DIR);

foreach $name (@names) {
    next if ( $name =~ /^\./ );
    if ( -d $name ) {
        print "found $dir directory: $name\n";
        next;
    }
    else {
        print "found $dir file: $name\n";
    }
}

相关内容

热门资讯

玩家必知教程!hhpoker作... 玩家必知教程!hhpoker作弊码(辅助挂)果然真的有挂(真实有挂)1、每一步都需要思考,不同水平的...
六分钟了解!pokemmo辅助... 六分钟了解!pokemmo辅助器(辅助挂)一贯是真的有挂(真的有挂)1、在pokemmo辅助器插件功...
普及知识!哈糖大菠萝有挂吗5个... 普及知识!哈糖大菠萝有挂吗5个常用方法(辅助挂)其实是真的有挂(有挂头条)1、哈糖大菠萝有挂吗5个常...
玩家必看分享!wepoker手... 玩家必看分享!wepoker手机版辅助(辅助挂)一贯真的是有挂(有挂头条)玩家必看分享!wepoke...
必看攻略!wepoker买钻石... 必看攻略!wepoker买钻石有用吗(辅助挂)切实有挂(有挂功能)所有人都在同一条线上,像星星一样排...