Friday, February 4, 2011

PERL : File I/O

pico fileio1.pl
#!/usr/bin/perl -w
#File are considered file handels. The file handle is stored in memory not on hard disk
#open (OUTFILE,"data1") #open file
#open (OUTFILE,">data1") #create file
#open (OUTFILE,">>data1") #append file
open (OUTFILE,"data1") || die "Problems: $!"; #die alow us to catch error in perl
$fullname= "Mark Sloan";
$min=1;
$max=20;
for ($min..$max)
{
print OUTFILE "$fullname\n";
}
#end
chmod u+x fileio1.pl
./fileio1.pl


#!/usr/bin/perl -w
open (INFILE,"data1") || die "Problems: $!"; #try to open a file that do not exists. The die method is called
while(<INFILE>)
{
print $_ #has each line from file at every iteration
}
#end


#!/usr/bin/perl -w
open (INFILE,"data1") || die "Problems: $!"; 
@data1contents = <INFILE>;
#print "@data1contents";
foreach (@data1contents)
{
print $_;
}
#end


#!/usr/bin/perl -w
open (INFILE,"data1") || die "Problems: $!"; 
$IN = "INFILE";
$OUT = "OUTFILE";
$filename = "data1";
open ($IN, "$filename") || die "Problems: $!";
@data1contents = <$IN>;
foreach (@data1contents)
{
print $_;
}
#end


#Read a file and copy it to another file
#!/usr/bin/perl -w
open (INFILE,"data1") || die "Problems: $!"; 
$IN = "INFILE";
$OUT = "OUTFILE";
$filenamein = "data1";
$filenameout = "data2";
open ($IN, "$<filenamein") || die "Problems: $!";#INPUT is by default
open ($OUT, ">$filenameout") || die "Problems: $!"; #OUTPUT file
@data1contents = <$IN>;
foreach (@data1contents)
{
if(/Mark/) #or s/Mark/Marko/
{
print $OUT $_;#prints to the $OUT filehandle.
}
}
#end
diff data1 data2 # the files are identicall
rm -rf data2


#!/usr/bin/perl -w
$FILEHANDLE = "FILEREADWRITE";
$filename = "data1";
$appendToFile = "Appends";
open (FILEHANDLE,"+<$filename") || die "Problems: $!"; #open for reading and write
#open (FILEHANDLE,"+>$filename") #this will erase the file
#open (FILEHANDLE,"+>>$filename") #this will appends the file
@data1contents = <$FILEHANDLE>;
foreach (@data1contents)
{
if(/Mark/) #or s/Mark/Marko/
{

}
print $FILEHANDLE $appendToFile;
}
#end
./fileio1.pl
tail -n1 data1 #Append
tail -n2 data1 # Mark Sloan and Append


#!/usr/bin/perl -w
$FILEHANDLE = "FILEREADWRITE";
$filename = "data1";
$appendToFile = "Appends";
open (FILEHANDLE,"ps -ax | ") || die "Problems: $!"; 
@data1contents = <$FILEHANDLE>;
foreach (@data1contents)
{
if (/httpd$/)
{
print $_;#prints only the httpd processes
}
}
#end
open($FILEHANDLE, "netstat -ant") or die $!;


#list content of a directory
pico opendir1.pl
#!/usr/bin/perl -w
$DIR = "/root/temp2/perl";
$DIRHANDLE = "HANDLE";
opendir ($DIRHANDLE, "$DIR") or die $!;
@dirlist = readdir ($DIRHANDLE);
foreach(@dirlist)
{
print $_\n;
}
#end


#!/usr/bin/perl -w
$DIR = "/etc";
@dirlist=`ls -A DIR`;
foreach(@dirlist)
{
print $_;#we don't need the new line character here
}
#end

No comments:

Post a Comment