Perl Files Notes 3

Reading from Files

my $var;
read (FILE, $var, 1024); #reading in block size

Similarly write(FILE, $var, 1024);
This works fantastically when dealing with binary files so that fetching and writing is fast and efficient.

Perl provides another set of functions sysread, syswrite

$written = syswrite(DATAFILE, $mystring, length($mystring));
die "syswrite failed: $!\n" unless $written == length($mystring);
$read = sysread(INFILE, $block, 256, 5);
warn "only read $read bytes, not 256" if 256 != $read;

The syswrite call sends the contents of $mystring to DATAFILE. The sysread call reads 256 bytes from INFILE and stores them 5 characters into $block, leaving its first 5 characters intact.

eg:

$var = "Header: ";
$cnt = sysread(FILE,$var, 10, length($var));
print $var;

OUTPUT:
Header: #!/usr/bin/perl
Here the read content is placted at the end of variable
10 specifies no of characters to be read,
length($var) specifies where ithe fetched contents are to be placed in output buffer.

Advertisements

About wikihead

A Seeker. Information Security Professional, Pursuing Life with Ayurveda.
This entry was posted in Notes and tagged , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s