1. ホーム
  2. スクリプト・コラム
  3. パール

ファイル操作に関するPerl学習メモ

2022-01-08 08:46:18

Perlのファイル操作は、ファイルを開く、読む、書くという点で、他の言語と似ています。
1. ファイルを開く

#! c:/perl/bin/perl -w 
use utf8; 
use strict; 
use warnings; 
 
my $filename = 'test.txt'; # or use absolute path, e.g.: c:/perl/Learn/test.txt 
 
if(open(MYFILE,$filename)) # MYFILE is a flag 
{ 
 printf "Can open this file:%s!", $filename;  
 close(MYFILE); 
} 
else{ 
 print "Can't open this file!"; 
} 


2. ファイルを読む

#! c:/perl/bin/perl -w 
use utf8; 
use strict; 
use warnings; 
 
my $filename = 'test.txt';  
if(open(MYFILE,$filename)) 
{ 
 my @myfile = <MYFILE>; # If you want to read multiple lines, use this method, if you only read one line: $myfile = <>; 
 my $count = 0; # the number of lines to read, the initial value is 0     
 printf "I have opened this file: %s\n", $filename; 
 while($count < @myfile){ #traversal 
  print ("$myfile[$count]\n"); #Note the way this is written. 
  $count++; 
 } 
 close(MYFILE); 
} 
else{ 
 print "I can't open this file!"; 
} 
exit; 


3. ファイルへの書き込み

#! c:/perl/bin/perl -w 
use utf8; 
use strict; 
use warnings; 
 
my $filename = 'test.txt';  
 
if(open(MYFILE,">>". $filename)) # this write, add not delete 
{ #This writes, rewrites the contents of the file MYFILE,">". $filename 
 print MYFILE "Write File appending Test\n"; 
 close(MYFILE); 
} 
else{ 
 print "I can't open this file!"; 
} 
exit;