麻豆小视频在线观看_中文黄色一级片_久久久成人精品_成片免费观看视频大全_午夜精品久久久久久久99热浪潮_成人一区二区三区四区

首頁 > 編程 > Perl > 正文

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

2020-06-04 20:27:51
字體:
供稿:網(wǎng)友

刪除文件

使用unlinke函數(shù),比如unlink $file, unlink $file1, $file2, $file3

打開文件

使用三參數(shù)的形式打開文件,這樣非常便于區(qū)分模式和文件名,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";

一次性讀入整個文件

使用<>在標(biāo)量環(huán)境下一次讀入一行,而在列表環(huán)境下一次讀入所有行,$/存儲的是行分隔符,默認(rèn)是換行符,我們先將$/改掉,這樣就可 以在標(biāo)量環(huán)境下一次讀入所有行了(這時已經(jīng)沒有行的概念了,就是讀入整個文件),你也可以用列表讀入所有行然后再將所有行拼到一起,但那樣速度很慢。用完 記得將$/改回來。
代碼如下:
#!/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關(guān)鍵字來將$/設(shè)置為局部變量,這樣跳出作用域后,$/又恢復(fù)了原來的值。
代碼如下:
#!/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;

最好的方法是使用模塊,這樣比自己寫安全,F(xiàn)ile::Slurp、IO::All都可以的。

打開文件請用雙引號

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

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 蜜桃一本色道久久综合亚洲精品冫 | 性盈盈盈影院 | 欧美性猛交一区二区三区精品 | 久久精品视频黄色 | 欧美一区二区黄 | 成年人网站视频免费 | 色阁阁69婷婷 | 成人三级免费电影 | 九一免费国产 | 精品国产一区二区三区天美传媒 | 欧美黄色看 | 国产亚洲综合一区二区 | h久久 | 久久6国产 | 91麻豆精品国产91久久久无需广告 | 成人午夜免费看 | 美国一级免费视频 | 亚洲影院在线 | va视频| 激情小说色 | 99精品视频久久精品视频 | 精品国产一区二区三区久久久 | 国产黄色录像片 | 欧美日韩精品中文字幕 | 国产成人精品无人区一区 | 中文字幕在线永久视频 | 黄网站免费入口 | xxxx69hd一hd| 久久精品亚洲成在人线av网址 | 在线观看麻豆 | 国产在线精品一区二区 | 国产精品自拍av | 成人免费观看49www在线观看 | 日韩黄a | 草莓视频在线导航 | 午夜视频在线观看免费视频 | 国产91久久久久久 | 国产午夜精品一区二区三区免费 | 黄色免费电影网址 | 国产在线观看91一区二区三区 | 久久久看|