Monday, 4 November 2019

perl read file - 15 ways

Method 1:


open(FH,'<file.txt') or die "Cant open file $!";

print FH;

close(FH);


Method 2:(read single line)


$var = readline(*STDIN);

print $var;

Method 3:(read single line)

open(my $fh, "<", "file.txt")

 or die "Cant open file $!";

 my $line = <$fh>;

 print "$line\n";

Method 4:(command line method)

while($a=<>)
{
    print $a;
}

Method 5:(read multilines)


while(<FH>)
{
print $_;
}

Method 6:(read in binary mode method)

open(FH,'<file.txt') or die "Cant open file $!";;

binmode FH, ":crlf";

while(<FH>)
{
print $_;
}

close(FH);

Method 7:(read in fixed length record files)

open(FH,'<file.txt')

$a=<FH>;

close(FH);

($f,$c)=unpack('packed values goes here',$a);

print "$f,$c\n";


Method 8:(read single line method)

open(FH,"-");

$fh = <FH>;
print $fh;


Method 9:(read  by byte method)

while(read(FH,$var,2))
{

push(@a,$var);

}


Method 10:(read character by method)

while(defined($var=getc FH))
{

print $var

}


Method 11:(file handle setter method)

open(FH,'<file.txt');

seek FH, 12,0;

while(<FH>)
{

print;

}

close(FH);


Method 12:(sysopen method)

sysopen(FH,"file.txt",O_RDONLY);

$line = <FH>;
print $line;


Method 13:(read by offset based method)

open(FH,'<file.txt');

while (read(FH,$var,2,4))
{

print $var;

}

close(FILE1);


Method 14:(linux call method) 

@file=system(cat file.txt);

print @file;


Method 15:(IO Module method) 

use IO::File;
$output = IO::File->new("file.txt",'r');
@var = <$output>;
print @var;


Labels:

0 Comments:

Post a Comment

Note: only a member of this blog may post a comment.

<< Home