Friday, July 18, 2008

Perl Write on file/Read File and some tips

#=====Write on File======

open(f,">c:\\1.txt") || die("Can't open");

$x=<>;

chop($x);

while ($x ne "")

{ print f ("$x\n");

$x=<>;

chop($x);

}

close(f);

#=====Read from File======

open(f,"c:\\x.txt") || die("Can't open");

$x=;

while ($x ne "")

{ print ("$x");

$x=;

}

close(f);

Tips for Reading File

#=====Reading Character ======

open(f,"c:\\1.txt") || die("Can't open");

$x=getc(f);

while ($x ne "")

{ print ("$x ");

$x=getc(f);

}

close(f);

#=====Reading By Array ======

open(f,"c:\\1.txt") || die("Can't open");

@a=;

print("@a")

#=====Copy File to Another ======

open(f,"C:\\x.txt") || die("Error");

open(w,">c:\\t.txt");

@x=;

print w ("@x");

close (f);

close (w);

#=====Copy File to Another But in reverse way ======

open(f,"C:\\1.txt") || die("Error");

open(w,">c:\\t.txt");

@x=;

@x=reverse(@x);

print w ("@x");

close (f);

close (w);

#=====Copy File to Another and find the repeat for each character and each word======

open(f,"C:\\x.txt") || die("Error");

$x=getc(f);

while($x ne "" )

{$a{$x}++;

$x=getc(f);}

close (f) ;

open(f,"C:\\x.txt") || die("Error");

$x=;

while($x ne "" )

{@x=split(/\s+/,$x);

for ($i=0;$i<@x;$i++)

{$b{$x[$i]}++;}

$x=;

}

close (f) ;

open(f,"C:\\x.txt") || die("Error");

@e=;

close (f) ;

open (f,">C:\\rr.txt");

print f ("\n======= The Array Sorted====================\n");

@e=sort(@e);

print f ("@e");

print f ("\n=========================================\n");

foreach $x (keys(%a))

{print f ("$x Repeted $a{$x}\n");}

foreach $r (keys(%b))

{print f ("$r Repeted $b{$r}\n");}

#=====Check The File State ======

$x="c:\\x.txt";

$r=-s $x;

print("$x = $r byte\n---\n");

if (-B $x)

{print("\n $x is Binary\n---\n");}

else

{print("The file is not Binary\n---\n");}

if (-x $x)

{print("\n $x is excutable\n---\n");}

else

{print("The file is not excutable\n---\n");}

if (-T $x)

{print(" $x is text\n---\n");}

else

{print("The file is not text\n---\n");}

if (-z $x)

{print("The file is empty");}

else

{print("The file is not empty");}

open (f,$x);

if (-r $x)

{print("\n---\n $x is readable");}

else

{print("\n---\nThe file is not readable");}

if (-w $x)

{print("\n---\n$x is writable");}

else

{print("\n---\nThe file is not writable");}


No comments: