Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • DSA
  • Practice Problems
  • C
  • C++
  • Java
  • Python
  • JavaScript
  • Data Science
  • Machine Learning
  • Courses
  • Linux
  • DevOps
  • SQL
  • Web Development
  • System Design
  • Aptitude
  • GfG Premium
Open In App
Next Article:
Perl | Writing to a File
Next article icon

Perl | Opening and Reading a File

Last Updated : 26 Feb, 2019
Comments
Improve
Suggest changes
Like Article
Like
Report
A filehandle is an internal Perl structure that associates a physical file with a name. All filehandles have read/write access, so once filehandle is attached to a file reading/writing can be done. However, the mode in which file handle is opened is to be specified while associating a filehandle.  
Opening a File
  Open function is used to open a new file or an existing file.
Syntax: open FILEHANDLE, VAR
Here FILEHANDLE is the handle returned by the open function and VAR is the expression having file name and mode of opening the file. The table given below shows the modes in which file can be opened and access to various operations.
ModeDescription
r or <Read Only Access
w or >Creates, Writes, and Truncates
a or >>Writes, Appends, and Creates
r+ or +<Reads and Writes
w+ or +>Reads, Writes, Creates, and Truncates
a+ or +>>Reads, Writes, Appends, and Creates
 
Reading a file
  Once a FILEHANDLE is assigned a file, various operations like reading, writing and appending can be done. There are a number of different ways of reading a file.
  • Using a File Handle Operator
  • Using getc function
  • Using read function
  • The FileHandle Operator The main method of reading the information from an open filehandle is using the operator < >. When < > operator is used in a list context, it returns a list of lines from the specified filehandle. The example below reads one line from the file and stores it in the scalar. Let the content of file "GFG.txt" is as given below:
      GeeksforGeeks  Hello Geek  Geek a revolution  Geeks are the best  
    Example: GFG.pl Perl
    # Opening the file  open(fh, "GFG.txt") or die "File '$filename' can't be opened";  # Reading First line from the file $firstline = <fh>; print "$firstline\n"; 
    Output :
  • getc Function The getc function returns a single character from the specified FILEHANDLE, or STDIN if none is specified
    Syntax: getc FILEHANDLE
    Perl
    # Opening the file  open(fh, "GFG.txt") or die "File '$filename' can't be opened";   # Reading First char from the file $firstchar = getc(fh); print "$firstchar\n"; 
    Output: If there was an error or the filehandle is at end of the file, then it returns undef.
  • read Function The read function is used to read binary data from a file using filehandle.
    Syntax read FILEHANDLE, SCALAR, LENGTH, OFFSET read FILEHANDLE, SCALAR, LENGTH
    Here, LENGTH represents the length of data to be read and the data is placed at the start of SCALAR if no OFFSET is specified. Otherwise, data is placed after bytes of OFFSET in SCALAR. On the success of file reading, the function returns the number of bytes read, zero at end of file, or undef if there was an error.
  •  
    Reading Multiple line at a time
      The example shown below reads the content of file specified by filehandle till it reaches End Of File(EOF). Example: File.pl Perl
    # Opening the file open(FH, "GFG.txt")or die "Sorry!! couldn't open"; print "Reading file \n";  # Reading the file till FH reaches EOF while(<FH>) {     # Printing one line at a time     print $_; } close; 
    Output :  
    Exception Handling in Files
      There are two ways in which Exception can be handled
    • Throw an exception if file cannot be opened
    • Give a warning if file cannot be opened and continue running
    • Throw an Exception When filehandle could not be assigned a valid file pointer at that time die gets executed printing the message and kills the current program. Example : Perl
      # Initializing filename  $filename = 'GFG1.txt';  # Prints an error and exits if file not found open(fh, '<', $filename) or die "Couldn't Open file $filename"; 
      Output: The above code prints an error if file not found and exits from the code.
    • Give a warning When filehandle could not be assigned a valid file pointer it just prints warning message using warn function and keeps running. Example : Perl
      # Initializing filename $filename = 'GFG.txt'; # Opening a file and reading content if(open(fh, '<', $filename)) {     while(<fh>)     {         print $_;     } }  # Executes if file not found else {   warn "Couldn't Open a file $filename"; } 
      Output:

      Next Article
      Perl | Writing to a File

      R

      rupanisweety
      Improve
      Article Tags :
      • Perl
      • Perl-files

      Similar Reads

        Basics

        Perl Programming Language
        Perl is a general purpose, high level interpreted and dynamic programming language. Perl supports both the procedural and Object-Oriented programming. Perl is a lot similar to C syntactically and is easy for the users who have knowledge of C, C++. Since Perl is a lot similar to other widely used lan
        3 min read
        Introduction to Perl
        Perl is a general-purpose, high level interpreted and dynamic programming language. It was developed by Larry Wall, in 1987. There is no official Full form of the Perl, but still, the most used expansion is "Practical Extraction and Reporting Language". Some of the programmers also refer Perl as the
        9 min read
        Perl Installation and Environment Setup in Windows, Linux, and MacOS
        Prerequisite: Introduction to Perl Before, we start with the process of Installing Perl on our System, whether it be Windows, Linux or Macintosh. We must have first-hand knowledge of What the Perl Language is and what it actually does?. Perl is a general purpose, high level interpreted and dynamic p
        3 min read
        Perl | Basic Syntax of a Perl Program
        Perl is a general purpose, high level interpreted and dynamic programming language. Perl was originally developed for the text processing like extracting the required information from a specified text file and for converting the text file into a different form. Perl supports both the procedural and
        10 min read
        Hello World Program in Perl
        Perl programming language is exclusively designed for text processing purposes. Its abbreviation denotes Practical Extraction and Report Language. It is compatible on various platforms, such as Windows, Mac OS, and almost all versions of UNIX. Hello World! program in every programming language gives
        3 min read

        Fundamentals

        Perl | Data Types
        Data types specify the type of data that a valid Perl variable can hold. Perl is a loosely typed language. There is no need to specify a type for the data while using in the Perl program. The Perl interpreter will choose the type based on the context of the data itself.  There are 3 data types in Pe
        3 min read
        Perl | Boolean Values
        In most of the programming language True and False are considered as the boolean values. But Perl does not provide the type boolean for True and False. In general, a programmer can use the term "boolean" when a function returns either True or False. Like conditional statements(if, while, etc.) will
        3 min read
        Perl | Operators | Set - 1
        Operators are the main building block of any programming language. Operators allow the programmer to perform different kinds of operations on operands. In Perl, operators symbols will be different for different kind of operands(like scalars and string). Operators Can be categorized based upon their
        12 min read
        Perl | Operators | Set - 2
        Operators are the main building block of any programming language. Operators allow the programmer to perform different kinds of operations on operands. In Perl, operators symbols will be different for different kind of operands(like scalars and string). Some of the operators already discussed in Per
        7 min read
        Perl | Variables
        Variables in Perl are used to store and manipulate data throughout the program. When a variable is created it occupies memory space. The data type of a variable helps the interpreter to allocate memory and decide what to be stored in the reserved memory. Therefore, variables can store integers, deci
        4 min read
        Perl | Modules
        A module in Perl is a collection of related subroutines and variables that perform a set of programming tasks. Perl Modules are reusable. Various Perl modules are available on the Comprehensive Perl Archive Network (CPAN). These modules cover a wide range of categories such as network, CGI, XML proc
        3 min read
        Packages in Perl
        A Perl package is a collection of code which resides in its own namespace. Perl module is a package defined in a file having the same name as that of the package and having extension .pm. Two different modules may contain a variable or a function of the same name. Any variable which is not contained
        4 min read

        Control Flow

        Perl | Decision Making (if, if-else, Nested–if, if-elsif ladder, unless, unless-else, unless-elsif)
        Decision Making in programming is similar to decision making in real life. In programming, a certain block of code needs to be executed when some condition is fulfilled. A programming language uses control statements to control the flow of execution of the program based on certain conditions. These
        6 min read
        Perl | Loops (for, foreach, while, do...while, until, Nested loops)
        Looping in programming languages is a feature which facilitates the execution of a set of instructions or functions repeatedly while some condition evaluates to true. Loops make the programmers task simpler. Perl provides the different types of loop to handle the condition based situation in the pro
        7 min read
        Perl | given-when Statement
        given-when statement in Perl is a substitute for long if-statements that compare a variable to several integral values. The given-when statement is a multiway branch statement. It provides an easy way to dispatch execution to different parts of code based on the value of the expression. given is a c
        4 min read
        Perl | goto statement
        The goto statement in Perl is a jump statement which is sometimes also referred to as unconditional jump statement. The goto statement can be used to jump from anywhere to anywhere within a function. Syntax: LABEL: Statement 1; Statement 2; . . . . . Statement n; goto LABEL; In the above syntax, the
        3 min read

        Arrays & Lists

        Perl | Arrays
        In Perl, array is a special type of variable. The array is used to store the list of values and each object of the list is termed as an element. Elements can either be a number, string, or any type of scalar data including another variable. Example: @number = (50, 70, 46); @names = ("Geeks", "For",
        6 min read
        Perl | Array Slices
        In Perl, array is a special type of variable. The array is used to store the list of values and each object of the list is termed as an element. Elements can either be a number, string, or any type of scalar data including another variable. Arrays can store any type of data and that data can be acce
        3 min read
        Perl | Arrays (push, pop, shift, unshift)
        Perl provides various inbuilt functions to add and remove the elements in an array. .string-table { font-family: arial, sans-serif; border-collapse: collapse; border: 1px solid #5fb962; width: 100%; } .string-table td, th { background-color: #c6ebd9; border: 1px solid #5fb962; text-align: left; padd
        3 min read
        Perl List and its Types
        Introduction to Lists A list is a collection of scalar values. We can access the elements of a list using indexes. Index starts with 0 (0th index refers to the first element of the list). We use parenthesis and comma operators to construct a list. In Perl, scalar variables start with a $ symbol wher
        4 min read

        Hash

        Perl Hash
        A hash is a set of key-value pairs. Perl stores elements of a hash such that it searches for the values based on its keys. Hash variables start with a '%' sign. Perl requires the keys of a hash to be strings, whereas the values can be any scalars. These values can either be a number, string or refer
        4 min read
        Perl | Hash Operations
        Prerequisite: Perl Hashes, Perl Hash As most readers likely know, the hash stores data by using a mechanism called Hashing. In hashing, a key is used to determine a value or data. These keys must be unique and are then used as the index at which the data associated with the key is stored. This data
        8 min read
        Perl | Multidimensional Hashes
        Prerequisite: Hashes-Basics Introduction Beyond the normal constraints of the hashes, we can also create complex structures made up of combinations of two. These are nested or complex structures and they can be used to model complex data in an easy-to-use format. Among all of the Perl's nested struc
        6 min read

        Scalars

        Perl | Scalars
        A scalar is a variable that stores a single unit of data at a time. The data that will be stored by the scalar variable can be of the different type like string, character, floating point, a large group of strings or it can be a webpage and so on.Example : Perl # Perl program to demonstrate # scalar
        2 min read
        Perl | Comparing Scalars
        Prerequisite: Scalars in Perl Perl has two types of comparison operator sets. Just like other mathematical operators, instead of performing operations, these operators compare scalars. There are two types of sets of Perl comparison operators. One is for numeric scalar values and one is for string sc
        6 min read
        Perl | scalar keyword
        scalar keyword in Perl is used to convert the expression to scalar context. This is a forceful evaluation of expression to scalar context even if it works well in list context. Syntax: scalar exprReturns: a scalar value Example 1: Perl #!/usr/bin/perl -w # Defining Arrays @array1 = ("Geeks
        2 min read

        Strings

        Perl | Quoted, Interpolated and Escaped Strings
        A string in Perl is a scalar variable and start with a ($) sign and it can contain alphabets, numbers, special characters. The string can consist of a single word, a group of words or a multi-line paragraph. The String is defined by the user within a single quote (‘) or double quote (“). Quoted Stri
        4 min read
        Perl | String Operators
        Operators are the foundation of any programming language. Thus, the functionality of Perl programming language is incomplete without the use of operators. A user can define operators as symbols that help to perform specific mathematical and logical computations on operands. String are scalar variabl
        4 min read
        Perl | String functions (length, lc, uc, index, rindex)
        String in Perl is a sequence of character enclosed within some kinds of quotation marks. Perl string can contain UNICODE, ASCII and escape sequence characters. Perl provides the various function to manipulate the string like any other programming language. Some string functions of Perl are as follow
        4 min read

        OOP Concepts

        Object Oriented Programming (OOPs) in Perl
        Object-oriented programming: As the name suggests, Object-Oriented Programming or OOPs refers to languages that uses objects in programming. Object-oriented programming aims to implement real-world entities like inheritance, hiding, polymorphism, etc in programming. The main aim of OOP is to bind to
        7 min read
        Perl | Classes in OOP
        In this modern world, where the use of programming has moved to its maximum and has its application in each and every work of our lives, we need to adapt ourselves to such programming paradigms that are directly linked to the real-world examples. There has been a drastic change in the competitivenes
        6 min read
        Perl | Objects in OOPs
        Perl is an Objected Oriented, dynamic and interpreter based programming language. In object-oriented programming, we have three main aspects, which are, object, class, and methods. An object is a data type which can be specifically called as an instance of the class to which it belongs. It can be a
        6 min read
        Perl | Methods in OOPs
        Methods are used to access and modify the data of an object. These are the entities which are invoked with the use of objects of a class or a package itself. Methods are basically a subroutine in Perl, there is no special identity of a method. Syntax of a method is the same as that of a subroutine.
        5 min read
        Perl | Constructors and Destructors
        Constructors Constructors in Perl subroutines returns an object which is an instance of the class. In Perl, the convention is to name the constructor "new". Unlike many other OOPs, Perl does not provide any special syntax for constructing an object. It uses Data structures(hashes, arrays, scalars) t
        4 min read
        Perl | Method Overriding in OOPs
        In any object-oriented programming language, Overriding is a feature that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its super-classes or parent classes. When a method in a subclass has the same name, same parameters or signat
        6 min read
        Perl | Inheritance in OOPs
        Inheritance is a key concept in object-oriented programming that allows you to define a new class based on an existing class. The new class, called a subclass or derived class, inherits all of the properties and methods of the existing class, called the superclass or base class, and can also define
        7 min read
        Perl | Polymorphism in OOPs
        Polymorphism is the ability of any data to be processed in more than one form. The word itself indicates the meaning as poly means many and morphism means types. Polymorphism is one of the most important concepts of object-oriented programming languages. The most common use of polymorphism in object
        4 min read
        Perl | Encapsulation in OOPs
        Encapsulation in Perl is the process of wrapping up of data to protect it from the outside sources which need not have access to that part of the code. Encapsulation is a part of the Object-oriented programming, it is used to bind the data and the subroutines that are used to manipulate that data. I
        6 min read

        Regular Expressions

        Perl | Regular Expressions
        Regular Expression (Regex or Regexp or RE) in Perl is a special text string for describing a search pattern within a given text. Regex in Perl is linked to the host language and is not the same as in PHP, Python, etc. Sometimes it is termed as “Perl 5 Compatible Regular Expressions“. To use the Rege
        2 min read
        Perl | Operators in Regular Expression
        Prerequisite: Perl | Regular Expressions The Regular Expression is a string which is the combination of different characters that provides matching of the text strings. A regular expression can also be referred to as regex or regexp. The basic method for applying a regular expression is to use of bi
        4 min read
        Perl | Regex Character Classes
        Character classes are used to match the string of characters. These classes let the user match any range of characters, which user don’t know in advance. Set of characters that to be matched is always written between the square bracket []. A character class will always match exactly for one characte
        3 min read
        Perl | Quantifiers in Regular Expression
        Perl provides several numbers of regular expression quantifiers which are used to specify how many times a given character can be repeated before matching is done. This is mainly used when the number of characters going to be matched is unknown. There are six types of Perl quantifiers which are give
        4 min read

        File Handling

        Perl | File Handling Introduction
        In Perl, file handling is the process of creating, reading, writing, updating, and deleting files. Perl provides a variety of built-in functions and modules that make it easy to work with files. Here's an introduction to file handling in Perl: File modes:When opening a file in Perl, you need to spec
        7 min read
        Perl | Opening and Reading a File
        A filehandle is an internal Perl structure that associates a physical file with a name. All filehandles have read/write access, so once filehandle is attached to a file reading/writing can be done. However, the mode in which file handle is opened is to be specified while associating a filehandle. Op
        4 min read
        Perl | Writing to a File
        A filehandle is a variable that is used to read and write to a file. This filehandle gets associated with the file. In order to write to the file, it is opened in write mode as shown below: open (FH, ‘>’, “filename.txt”); If the file is existing then it truncates the old content of file with the
        3 min read
        Perl | Useful File-handling functions
        Perl was originally developed for the text processing like extracting the required information from a specified text file and for converting the text file into a different form. These operations can be performed by the use of various inbuilt file functions. Example: Perl #!/usr/bin/perl # Opening a
        2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences