Example Reading Different Variables From a File in Perl

Perl - File I/O


The basics of treatment files are elementary: you acquaintance a filehandle with an external entity (unremarkably a file) and then use a diversity of operators and functions within Perl to read and update the data stored within the data stream associated with the filehandle.

A filehandle is a named internal Perl structure that associates a physical file with a proper noun. All filehandles are capable of read/write admission, so y'all can read from and update whatsoever file or device associated with a filehandle. However, when yous acquaintance a filehandle, you tin specify the fashion in which the filehandle is opened.

Three basic file handles are - STDIN, STDOUT, and STDERR, which represent standard input, standard output and standard error devices respectively.

Opening and Closing Files

There are post-obit two functions with multiple forms, which can be used to open any new or existing file in Perl.

open FILEHANDLE, EXPR open FILEHANDLE  sysopen FILEHANDLE, FILENAME, Way, PERMS sysopen FILEHANDLE, FILENAME, Manner        

Here FILEHANDLE is the file handle returned by the open part and EXPR is the expression having file proper name and fashion of opening the file.

Open Function

Post-obit is the syntax to open file.txt in read-only mode. Here less than < sign indicates that file has to be opend in read-only mode.

open(Data, "<file.txt");        

Hither Information is the file handle, which volition be used to read the file. Hither is the case, which volition open a file and will print its content over the screen.

#!/usr/bin/perl  open(Data, "<file.txt") or die "Couldn't open file file.txt, $!";  while(<DATA>) {    print "$_"; }        

Following is the syntax to open file.txt in writing manner. Here less than > sign indicates that file has to be opend in the writing way.

open(Data, ">file.txt") or die "Couldn't open up file file.txt, $!";        

This example actually truncates (empties) the file before opening it for writing, which may not exist the desired outcome. If you desire to open a file for reading and writing, you tin can put a plus sign before the > or < characters.

For example, to open up a file for updating without truncating it −

open(DATA, "+<file.txt"); or die "Couldn't open file file.txt, $!";        

To truncate the file offset −

open Data, "+>file.txt" or die "Couldn't open file file.txt, $!";        

You lot can open a file in the append mode. In this mode, writing point will exist set to the end of the file.

open up(Data,">>file.txt") || die "Couldn't open up file file.txt, $!";        

A double >> opens the file for appending, placing the file pointer at the end, so that you tin immediately starting time appending data. However, you can't read from information technology unless y'all too place a plus sign in front of it −

open(DATA,"+>>file.txt") || die "Couldn't open up file file.txt, $!";        

Following is the table, which gives the possible values of different modes

Sr.No. Entities & Definition
ane

< or r

Read Only Admission

2

> or due west

Creates, Writes, and Truncates

3

>> or a

Writes, Appends, and Creates

iv

+< or r+

Reads and Writes

5

+> or westward+

Reads, Writes, Creates, and Truncates

6

+>> or a+

Reads, Writes, Appends, and Creates

Sysopen Function

The sysopen office is similar to the master open office, except that it uses the system open() function, using the parameters supplied to it as the parameters for the organization role −

For example, to open a file for updating, emulating the +<filename format from open −

sysopen(DATA, "file.txt", O_RDWR);        

Or to truncate the file before updating −

sysopen(Data, "file.txt", O_RDWR|O_TRUNC );        

You can use O_CREAT to create a new file and O_WRONLY- to open file in write simply style and O_RDONLY - to open file in read only way.

The PERMS argument specifies the file permissions for the file specified, if information technology has to exist created. Past default it takes 0x666.

Following is the tabular array, which gives the possible values of MODE.

Sr.No. Entities & Definition
one

O_RDWR

Read and Write

2

O_RDONLY

Read But

3

O_WRONLY

Write Only

4

O_CREAT

Create the file

5

O_APPEND

Suspend the file

6

O_TRUNC

Truncate the file

7

O_EXCL

Stops if file already exists

eight

O_NONBLOCK

Non-Blocking usability

Close Part

To close a filehandle, and therefore disassociate the filehandle from the respective file, you apply the close function. This flushes the filehandle's buffers and closes the organisation's file descriptor.

shut FILEHANDLE close        

If no FILEHANDLE is specified, then it closes the currently selected filehandle. Information technology returns true only if it could successfully flush the buffers and close the file.

close(DATA) || die "Couldn't close file properly";        

Reading and Writing Files

Once you have an open filehandle, you need to be able to read and write information. There are a number of different ways of reading and writing data into the file.

The <FILEHANDL> Operator

The main method of reading the information from an open filehandle is the <FILEHANDLE> operator. In a scalar context, information technology returns a single line from the filehandle. For instance −

#!/usr/bin/perl  print "What is your name?\n"; $proper noun = <STDIN>; print "How-do-you-do $name\due north";        

When you employ the <FILEHANDLE> operator in a list context, it returns a list of lines from the specified filehandle. For example, to import all the lines from a file into an array −

#!/usr/bin/perl  open(Information,"<import.txt") or die "Tin't open data"; @lines = <DATA>; close(DATA);        

getc Function

The getc part returns a single grapheme from the specified FILEHANDLE, or STDIN if none is specified −

getc FILEHANDLE getc        

If at that place was an error, or the filehandle is at end of file, then undef is returned instead.

read Function

The read part reads a cake of data from the buffered filehandle: This function is used to read binary information from the file.

read FILEHANDLE, SCALAR, LENGTH, Kickoff read FILEHANDLE, SCALAR, LENGTH        

The length of the information read is divers by LENGTH, and the information is placed at the first of SCALAR if no OFFSET is specified. Otherwise data is placed after OFFSET bytes in SCALAR. The function returns the number of bytes read on success, zero at end of file, or undef if there was an mistake.

print Function

For all the different methods used for reading information from filehandles, the primary function for writing information back is the print office.

impress FILEHANDLE LIST print LIST impress        

The print role prints the evaluated value of LIST to FILEHANDLE, or to the electric current output filehandle (STDOUT by default). For case −

print "How-do-you-do World!\northward";        

Copying Files

Here is the example, which opens an existing file file1.txt and read information technology line by line and generate another copy file file2.txt.

#!/usr/bin/perl  # Open file to read open(DATA1, "<file1.txt");  # Open new file to write open(DATA2, ">file2.txt");  # Copy data from 1 file to some other. while(<DATA1>) {    print DATA2 $_; } close( DATA1 ); close( DATA2 );        

Renaming a file

Here is an example, which shows how we can rename a file file1.txt to file2.txt. Bold file is available in /usr/test directory.

#!/usr/bin/perl  rename ("/usr/test/file1.txt", "/usr/test/file2.txt" );        

This part renames takes two arguments and it simply renames the existing file.

Deleting an Existing File

Hither is an case, which shows how to delete a file file1.txt using the unlink function.

#!/usr/bin/perl  unlink ("/usr/test/file1.txt");        

Positioning inside a File

Yous tin employ to tell role to know the current position of a file and seek part to indicate a particular position inside the file.

tell Role

The beginning requirement is to find your position within a file, which you do using the tell office −

tell FILEHANDLE tell        

This returns the position of the file pointer, in bytes, inside FILEHANDLE if specified, or the current default selected filehandle if none is specified.

seek Part

The seek office positions the file arrow to the specified number of bytes within a file −

seek FILEHANDLE, POSITION, WHENCE        

The role uses the fseek organization function, and you have the aforementioned ability to position relative to three different points: the commencement, the cease, and the current position. You lot do this by specifying a value for WHENCE.

Zero sets the positioning relative to the start of the file. For instance, the line sets the file pointer to the 256th byte in the file.

seek DATA, 256, 0;        

File Information

Yous tin test certain features very rapidly within Perl using a serial of test operators known collectively equally -X tests. For instance, to perform a quick test of the various permissions on a file, you might utilize a script like this −

#/usr/bin/perl  my $file = "/usr/examination/file1.txt"; my (@description, $size); if (-eastward $file) {    push @clarification, 'binary' if (-B _);    button @clarification, 'a socket' if (-Due south _);    push @clarification, 'a text file' if (-T _);    button @description, 'a block special file' if (-b _);    push @description, 'a character special file' if (-c _);    push @description, 'a directory' if (-d _);    button @description, 'executable' if (-x _);    push @description, (($size = -s _)) ? "$size bytes" : 'empty';    print "$file is ", join(', ',@description),"\n"; }        

Hither is the list of features, which y'all can check for a file or directory −

Sr.No. Operator & Definition
i

-A

Script start time minus file last access fourth dimension, in days.

ii

-B

Is it a binary file?

3

-C

Script start time minus file last inode change time, in days.

3

-M

Script commencement time minus file modification time, in days.

4

-O

Is the file owned by the real user ID?

v

-R

Is the file readable past the existent user ID or real group?

half dozen

-S

Is the file a socket?

7

-T

Is it a text file?

8

-W

Is the file writable by the existent user ID or real group?

9

-X

Is the file executable by the existent user ID or real group?

10

-b

Is it a block special file?

11

-c

Is it a character special file?

12

-d

Is the file a directory?

xiii

-eastward

Does the file exist?

14

-f

Is information technology a plain file?

fifteen

-grand

Does the file have the setgid bit set?

sixteen

-k

Does the file have the viscid chip gear up?

17

-fifty

Is the file a symbolic link?

18

-o

Is the file endemic past the constructive user ID?

19

-p

Is the file a named pipe?

20

-r

Is the file readable by the effective user or group ID?

21

-s

Returns the size of the file, zero size = empty file.

22

-t

Is the filehandle opened by a TTY (final)?

23

-u

Does the file have the setuid bit set?

24

-due west

Is the file writable by the constructive user or group ID?

25

-x

Is the file executable by the constructive user or group ID?

26

-z

Is the file size goose egg?

Useful Video Courses


Perl Online Training

Video

COMPLETE PERL Programming

Video

Perl for Beginners: Learn A to Z of Perl Scripting Hands-on

Video

Hyperledger Fabric 2.x - First Practical Blockchain

Video

garrettcapperes.blogspot.com

Source: https://www.tutorialspoint.com/perl/perl_files.htm

0 Response to "Example Reading Different Variables From a File in Perl"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel