perl幾個文件操作例子

字號:


    perl用的最多的地方就算是文件處理了,下面我就總結了一下perl文件操作的一些東西,并且有具體的例子,通過下面的例子,加強我們對perl文件操作的理解。
    刪除文件
    使用unlinke函數,比如unlink $file, unlink $file1, $file2, $file3
    打開文件
    使用三參數的形式打開文件,這樣非常便于區(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;
    一次性讀入整個文件
    使用<>在標量環(huán)境下一次讀入一行,而在列表環(huán)境下一次讀入所有行,$/存儲的是行分隔符,默認是換行符,我們先將$/改掉,這樣就可 以在標量環(huán)境下一次讀入所有行了(這時已經沒有行的概念了,就是讀入整個文件),你也可以用列表讀入所有行然后再將所有行拼到一起,但那樣速度很慢。用完記得將$/改回來。
    代碼如下:
    #!/usr/bin/perl
    use strict ;
    use warnings ;
    sub test{
    open file, '<', d:/code/test.txt or die $! ;
    my $olds = $/ ;
    $/ = undef ;
    my $slurp = ;
    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 = ;
    print $slurp, n ;
    }
    &test() ;
    最好的方法是使用模塊,這樣比自己寫安全,file::slurp、io::all都可以的。
    打開文件請用雙引號
    open文件時,如果文件名有變量替換,最好用雙引號而不是單引號,因為單引號無視變量內插。
    代碼如下:
    open file <$file or die $! ; #這樣可以。
    open file '<$file' or die $! ; #這樣就不可以,因為$file不會被解釋成變量內插。同樣<也不會被解釋成輸入
    文件句柄作參數
    假設有一個函數test,它有一個參數,是某個文件句柄,那么該如何傳遞這個參數呢?
    方法一,傳遞參數時,在句柄前面加*
    代碼如下:
    sub main {
    open file, '+<', 'test.data' or die $!;
    &test(*file);
    close file;
    }
    方法二,使用open my $file的形式打開文件
    代碼如下:
    sub main {
    open my $file, '+<', 'test.data' or die $!;
    &test($file);
    close $file;
    }