国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Perl > 正文

perl文件操作詳細教程

2020-02-23 19:47:35
字體:
來源:轉載
供稿:網友

  Perl有個強大的文件和文件夾操作功能,今天小編跟大家分享一篇perl文件操作詳細教程,感興趣的朋友跟小編一起來了解一下吧!

  刪除文件

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

  打開文件

  使用三參數的形式打開文件,這樣非常便于區分模式和文件名,perl 5.6之后的版本都支持這種方式。

  復制代碼 代碼如下:

  #Open the 'txt' file for reading

  open FH, '

  #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, '+

  #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, '

  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, '

  my $slurp = ;

  print $slurp, "/n" ;

  }

  &test() ;

  1;

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

  打開文件請用雙引號

  open文件時,如果文件名有變量替換,最好用雙引號而不是單引號,因為單引號無視變量內插。

  復制代碼 代碼如下:

  open FILE "

  open FILE '

  文件句柄作參數

  假設有一個函數test,它有一個參數,是某個文件句柄,那么該如何傳遞這個參數呢?

  方法一,傳遞參數時,在句柄前面加*

  復制代碼 代碼如下:

  sub main {

  open FILE, '+

  &test(*FILE);

  close FILE;

  }

  方法二,使用open my $FILE的形式打開文件

  復制代碼 代碼如下:

  sub main {

  open my $FILE, '+

  &test($FILE);

  close $FILE;

  }

  以上就是perl文件操作詳細教程,想必都了解了吧,更多相關內容請繼續關注武林技術頻道。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表

圖片精選

主站蜘蛛池模板: 白城市| 合阳县| 酉阳| 海伦市| 华阴市| 利辛县| 焦作市| 凤翔县| 通江县| 陆丰市| 沂水县| 四川省| 济南市| 吴川市| 丰顺县| 淳安县| 盘锦市| 饶阳县| 晋宁县| 高安市| 江华| 丰都县| 凤台县| 山东| 泰和县| 辛集市| 石台县| 东阳市| 远安县| 华容县| 儋州市| 罗江县| 博罗县| 井研县| 增城市| 龙海市| 陇西县| 万全县| 雅安市| 伊春市| 伊春市|