a亚洲精品_精品国产91乱码一区二区三区_亚洲精品在线免费观看视频_欧美日韩亚洲国产综合_久久久久久久久久久成人_在线区

首頁 > 編程 > Perl > 正文

perl文件操作的一些例子分享

2020-06-04 20:27:51
字體:
來源:轉載
供稿:網友

刪除文件

使用unlinke函數,比如unlink $file, unlink $file1, $file2, $file3

打開文件

使用三參數的形式打開文件,這樣非常便于區分模式和文件名,perl 5.6之后的版本都支持這種方式。
代碼如下:
#Open the 'txt' file for reading
open FH, '<', "$file_name.txt" or die "Error:$!/n";
#Open the 'txt' file for writing. Creates the #file_name if it doesn't already exist #and will delete/overwrite a pre-existing file of the same name
open FH, '>', "$file_name.txt" or die "Error:$!/n";
#Open the 'txt' file for appending. Creates the #file_name if it doesn't already exist
open FH, '>>', "$file_name.txt" or die "Error:$!/n";
#Open the 'txt' file for a 'read/write'. #Will not create the file if it doesn't #already exist and will not delete/overwrite #a pre-existing file of the same name
open FH, '+<', "$file_name.txt" or die "Error:$!/n";
#Open the 'txt' file for a 'read/write'. Will create #the file if it doesn't already exist and will #delete/overwrite a pre-existing file #of the same name
open FH, '+>', "$file_name.txt" or die "Error:$!/n";
#Open the 'txt' file for a 'read/append'. Will create #the file if it doesn't already exist and will #not delete/overwrite a pre-existing file #of the same name
open FH, '+>>', "$file_name.txt" or die "Error:$!/n";

一次性讀入整個文件

使用<>在標量環境下一次讀入一行,而在列表環境下一次讀入所有行,$/存儲的是行分隔符,默認是換行符,我們先將$/改掉,這樣就可 以在標量環境下一次讀入所有行了(這時已經沒有行的概念了,就是讀入整個文件),你也可以用列表讀入所有行然后再將所有行拼到一起,但那樣速度很慢。用完 記得將$/改回來。
代碼如下:
#!/usr/bin/perl
use strict ;
use warnings ;
sub test{
    open FILE, '<', "d:/code/test.txt" or die $! ;
    my $olds = $/ ;
    $/ = undef ;
    my $slurp = <FILE> ;
    print $slurp, "/n" ;
    $/ = $olds ;
    close FILE;
}
&test() ;

也可以使用local關鍵字來將$/設置為局部變量,這樣跳出作用域后,$/又恢復了原來的值。
代碼如下:
#!/usr/bin/perl
use strict ;
use warnings ;
sub test{
    local $/ ; #??? local $/ = undef ;
    open FILE, '<', "d:/code/zdd.txt" or die $! ;
    my $slurp = <FILE> ;
    print $slurp, "/n" ;
}
&test() ;
1;

最好的方法是使用模塊,這樣比自己寫安全,File::Slurp、IO::All都可以的。

打開文件請用雙引號

open文件時,如果文件名有變量替換,最好用雙引號而不是單引號,因為單引號無視變量內插。
代碼如下:
open FILE "<$file" or die $! ; #這樣可以。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 一区二区国产精品 | 国产在线观| 涩涩视频在线看 | 国产精品毛片一区二区 | 精品一区二区三区久久 | 亚洲精品一区二三区不卡 | 在线观看中文 | 中文亚洲 | 高清国产视频 | 久久久噜噜噜www成人网 | 蜜臀av性久久久久av蜜臀妖精 | 日韩视频免费在线 | 精品国产一区二区三区国产馆杂枝 | 麻豆二区 | 欧美成人手机在线 | 欧美日韩精品在线一区 | 视频一区二区三区在线观看 | 色吧av| 国产精品久久久久久久久久久久久久 | 欧美大片高清免费观看 | 久99视频| 成人综合视频在线 | 色在线免费视频 | 一区二区久久久 | 一级黄色爱爱视频 | 成人18视频在线观看 | 久久久www成人免费精品 | 国产精品4hu.www | 欧美综合视频 | 久久一卡二卡 | 国产综合视频在线观看 | 在线观看理论电影 | 国产一区二区在线看 | 人人爱干 | a天堂中文在线 | 成人在线国产 | 欧美精品一区二区在线观看 | 日韩性精品 | 黄色免费av | 麻豆精品国产91久久久久久 | 日日草影院 |