Solved

Random Access Files in PERL

Posted on 1997-06-23
3
164 Views
Last Modified: 2006-11-17
I want to be able to have random access files where I can read a particular record, or rewrite a particular record somewhat like I do in Visual Basic.  I have several Sams books on PERL but can find nothing about random access file handling.  Can anyone point me in the right direction or tell me how to do it?
I want to use it in a flat file database application.
0
Comment
Question by:donb1
3 Comments
 
LVL 5

Expert Comment

by:julio011597
ID: 1204342
seek() is what you need, and read() and print(); have a look at these functions.

-julio
0
 
LVL 5

Accepted Solution

by:
icd earned 100 total points
ID: 1204343
As an example, you can create a fixed length record file as follows. This example holds integers (four bytes ones) and allows random access to them.

--- cut here ---
# Create a file with four integer

$foo = pack("iiii", 0, 1, 2, 3);
open (FID, ">pack.dat");
print FID $foo;
close (FID);

# random access to record 2

$sizeofint = 4;

open (FID, "pack.dat");
seek(FID,2*$sizeofint,0);
read(FID, $buf, $sizeofint);
close(FID);

$foo = unpack("i", $buf);
print "The unpacked value is $foo\n";
--- end ---

0
 

Expert Comment

by:stevemanes
ID: 1204344
However, to retrieve a particular record from a file which was written by multiple pack()s you will need to know the length of the data record to know the offset to the beginning of record 'n'.  Since perl doesn't use structures like C, the quick and dirty way is to read the length() of the output from pack() and save it for future references.
0

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

A year or so back I was asked to have a play with MongoDB; within half an hour I had downloaded (http://www.mongodb.org/downloads),  installed and started the daemon, and had a console window open. After an hour or two of playing at the command …
There are many situations when we need to display the data in sorted order. For example: Student details by name or by rank or by total marks etc. If you are working on data driven based projects then you will use sorting techniques very frequently.…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…

840 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question