Thursday, October 14, 2010

File Handle

# Program to read directory
use warnings;
# file contains first line as 'helo' and second line as 'world'
$\ = "\n"; # newline character added after each print statement
# $* = 1;    # for multi line reading
open(LOG, '<C:/test.txt') || die "can't open";
print "opened";
while(<LOG>)
{
  #chop($_);  # removes last character in the line or word
  print $_;
  if ($_ =~ "helo")
  {
    print "Yes its helo";
  }
  else
  {
    print "else part - world";
  }
}
# working with directories
opendir(DIR, "C:/parent") || die "can't open directory";
@arr = readdir(DIR);
print join("::",@arr);
$len = @arr;
print $len;
rewinddir(DIR); # rewind is used to move to first position
while($file=readdir(DIR))
{
$pos = telldir(DIR);  # to get the position
print $file;
print $pos;
  if ($pos==30)
  {
    #  if you uncomment this line, it will run as infinite loop
    #  Seekdir is used to goto specified position
    # seekdir(DIR,5);
    print "go back to pos 30";
  }
}
mkdir("C:/parent/child4",0777);
rmdir("C:/parent/child4");
print "error ::".$!;    # . is used to concatenate two text messages.
# creates file if its not created, using > or >>(append), < readonly won't create file.
open(FHDLE, '>>C:/parent/abc.txt') || die "can't open";
# below print statement will write welcome in the file.
print FHDLE "welcome";
print FHDLE "Ananya";
# if we delete text in abc1, abc text also will get delete
# In Unix we can create file like below:
# system(touch "../abc.txt");
link("C:/parent/abc.txt","C:/parent/link.txt");
unlink("C:/parent/link.txt");
#print unlink("C:/parent/abc1.txt");

No comments:

Post a Comment

 

©2010 Software Testing powered by Free Blogger Templates | Author : Anand Satish