Beruflich Dokumente
Kultur Dokumente
Write File
In this article, let us discuss how to manipulate the file handlers in Perl.
open FH,"</tmp/msg";
open FH,"</tmp/msg";
$line = <FH>;
print $line;
open FH,">/tmp/msg";
print FH "Perl - Practical Extraction Report Language\n";
If you want to pass this handler to a perl function, you would use typeglob as shown below.
#!/usr/bin/perl
open FH,"</tmp/msg";
read_text(*FH);
sub read_text
{
local *FH = shift;
my @lines;
@lines = <FH>;
print @lines;
}
use IO::File;
$read_fh = IO::File->new("/tmp/msg",'r');
read_text($read_fh);
sub read_text
{
local $read_fh = shift;
my @lines;
@lines = <$read_fh>;
print @lines;
}
Following perl code snippet explains perl write operation with IO::File module.
$write_fh = IO::File->new("/tmp/msg",'w');
The below code reads first line from the /tmp/text file and immediately does the write operation.
#!/usr/bin/perl
open(FH,"+</tmp/text");
read_line(*FH);
write_line(*FH,"222\n");
sub read_line
{
local *FH = shift;
my $lines;
$line = <FH>;
print $line;
}
sub write_line
{
local *FH = shift;
print FH @_;
}
close(FH);
$ cat /tmp/text
one
222
three
four
five
open(OUT,">-");
open(IN,"-");
print "STDIN opened with the name as IN";
$input = <IN>;
sysopen(FH,"/tmp/text",O_RDONLY);
$line = <FH>;
print $line;
sysopen(FH,"/tmp/text",O_WRONLY);
If the above code is unable to open the file “/tmp/text”, it returns failure, and die gets executed. And the
“$!” Buildin variable contains the reason for open function failure.