Skip to content
geeksforgeeks
  • 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
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Practice Problems
  • Python
  • C
  • C++
  • Java
  • Courses
  • Machine Learning
  • DevOps
  • Web Development
  • System Design
  • Aptitude
  • Projects
Open In App
Next Article:
Perl | Pass By Reference
Next article icon

Perl | References to a Subroutine

Last Updated : 10 Jul, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Prerequisite: Perl references
 

Declaring References to a Subroutine


In Perl, a reference is, exactly as the name suggests, a reference or pointer to another object. References actually provide all sorts of abilities and facilities that would not otherwise be available and can be used to create sophisticated structures such as Dispatch tables, Higher-order procedures, Closures, etc. For C programmers using Perl for the first time, a reference is exactly like a pointer, except within Perl it’s easier to use and, more to the point, more practical. There are two types of references: symbolic and hard. 
Symbolic reference enables you to use the value of another variable as a reference to a variable by name. For example, if the variable $val contains the string "Text", the symbolic reference to $val refers to the variable $Text. 
A hard reference is a term for actual data that is contained in a data structure. However, the form of the data structure to which it points is largely irrelevant. Although a hard reference can refer to a single scalar, it can also refer to an array of scalars, a hash, or a subroutine.

$val = "Text"; $val_ref = \$val;  # For other variables $array = \@ARGV; $hash = \%ENV;  # For reference to subroutine sub val { print "val" }; $valsub = \&val;


 

Calling a subroutine Reference


Calling a subroutine reference is also known as dereferencing. It is the act of extracting information from the structures. When you dereference a scalar reference, you are in fact referring to the original data structure. The most direct approach of dereferencing a reference is to prepend the relevant data type character ($ for scalars, @ for arrays, % for hashes, and & for subroutines) that you simply expect before of the scalar variable containing the reference.

$val_ref = \$val;       # Create reference to scalar $array = \@ARGV;        # Create reference to array $hash = \%ENV;          # Create reference to hash $valsub = \&            # Create reference to subroutine  # Dereferencing $$val_ref; $$array[0, 1, ....]; $$hash{'...'}; &$valsub;


 

Note: The act of dereferencing information must be explicit. There is no implicit dereferencing supported within Perl on any structure.


Subroutines can be both named as well as anonymous. Perl provides the facility to declare references to both the types of subroutines and to dereference them. 
Example 1: 

perl
#!/usr/bin/perl  # Perl program to demonstrate # reference to subroutines  # Creating a named subroutine sub name {     return "GeeksforGeeks"; }  # Create callable reference  # to named subroutine $rs1 = \&name;      print("Reference to named subroutine: ", $rs1); print("\nAfter dereferencing, value : ", &$rs1);   # Create a reference to an  # anonymous subroutine $rs2 = sub{                return "GFG";           };  print("\n"); print("\nReference to anonymous subroutine: ", $rs2); print("\nAfter dereferencing, value : ", &$rs2);  

Output
Reference to named subroutine: CODE(0x981750) After dereferencing, value : GeeksforGeeks  Reference to anonymous subroutine: CODE(0x981870) After dereferencing, value : GFG

The use of infix operation is shown in the below example. The infix operation provides a better and easier way of extracting information from the complex or nested structures.
Example 2: 

perl
#!/usr/bin/perl  # Perl program to demonstrate # reference to subroutines  $rs = \&func1;  # Prints "GeeksforGeeks" $rs->("Geeks")->("for")->("Geeks");       sub func1 {     my $val = shift;     print "$val";     return \&func2; }  sub func2 {     my $val = shift;     print "$val";     return \&func3; }   sub func3  {     my $val = shift;     print "$val\n"; } 

Output: 
GeeksforGeeks

 

Callbacks

Callbacks is one of the important element that one should remember when developing Perl Tk interfaces. It calls back a piece of code from another part of the script when we reach a certain point of condition or perform a certain action. 
Callbacks are somewhat like a delayed execution of code, which is triggered by an event instead of executing things in a linear way. For such event-driven functionality of code, we often make use of subroutine references to call such pieces of code when required.
Example: 

Perl
# Perl program to demonstrate  # the use of callbacks sub alt {             print "$a $b\n";             $arr{$a} cmp $arr{$b};         }  %arr = ("Marcelo", "Lewis",         "Rodrygo", "Peter",         "Sandro", "James");  # @names = sort alt (keys(%arr)); @names = calc ("Alternate", keys(%arr)); foreach $person (@names)  {     print "$person teams up with $arr{$person}\n"; }  # Example code to show  # what really goes on inside sort. sub calc  {     my ($subn, @final) = @_;     for ($k = 0; $k < $final; $k++)      {         $count = 0;         for ($j = 0; $j < $final - $k; $j++)          {             $a = $final[$j];             $b = $final[$j + 1];             if (&{$subn}() > 0 )             {                 $final[$j] = $b;                 $final[$j + 1] = $a;                 $count++;             }         }         last unless ($count);     }     return @final } 

Output: 
Sandro teams up with James Rodrygo teams up with Peter Marcelo teams up with Lewis

 

The above example depicts the sorting of a list of hash keys based on the number of characters (length) in the value held in the hash using a callback function calc.
 

Arrays and Hashes of References


Beyond the normal constraints of arrays and hashes, you can also create complex structures made up of combinations of the two. These are nested, or complex structures and they can be used to model complex data in an easy-to-use format. What actually happens with a nested structure is that Perl stores the nested data type as a reference to an anonymous variable. For example, in a two-dimensional array, the main array is a list of references, and the sub-arrays are anonymous arrays to which these references point. This means that an “array of arrays” actually means an array of references to arrays. The same is true for all nested structures; and, although it seems complex, it does provide a suitably powerful method for creating complex, nested structures.
Example 1: 

perl
w # Perl program to demonstrate # array of references  # Declaring a reference to a nested array $array = [[1, 2, 3, 4, 5],            ['Geeks', 'for', 'Geeks'],            [6, 7, 8, 9]];  # Access element using index # Dereferencing performed print("$$array[1][2]");       # Access element using infix method print("\n$array->[1][1]"); print("\n$array->[1]->[0]");  # Printing complete nested array print("\nElements in the array are :"); print("\n"); for(my $i = 0; $i < scalar(@{$array}); $i++) {     for(my $j = 0;              $j < scalar(@{$array->[$i]}); $j++)     {         print($$array[$i][$j]);         print(" ");     }     print("\n"); } 

Output: 
Geeks for Geeks Elements in the array are : 1 2 3 4 5  Geeks for Geeks  6 7 8 9

 

Example 2:

perl
#!/usr/bin/perl  # Perl program to demonstrate # array of references use strict; use warnings;  my %friends = ( 1 => 'John',     4 => 'Sandro',                 2 => 'Rodrygo', 5 => 'Peter',                 3 => 'Marcelo', 6 => 'Luis' );  # Declaring a Reference to the hash my $hash_ref = \%friends;  # Access element from hash using key value print("$$hash_ref{1}\n");     # prints John  # Access element using infix operation print("$hash_ref->{3}\n");  # Print all elements of the hash # with their keys print ("The hash stored is :\n");  for (keys %$hash_ref) {     print("$_ = $hash_ref->{$_}\n"); } 

Output: 
John Marcelo The hash stored is : 4 = Sandro 1 = John 2 = Rodrygo 5 = Peter 3 = Marcelo 6 = Luis

 

Next Article
Perl | Pass By Reference

B

BhavikBothra
Improve
Article Tags :
  • Perl

Similar Reads

  • Perl | Scope of a Subroutine
    Subroutines in Perl, are reusable unit of code. It is a dynamic concept. Functions and subroutines are the two terms that can be used interchangeably. If you want to be strict on the semantics, small pieces of named blocks of code that accept arguments and return values are called subroutines. The b
    7 min read
  • Perl | Recursive Subroutines
    Prerequisite: Recursion in PerlRecursive means about or using a rule or procedure that can be applied repeatedly. It is the process of defining a function or calculating a number by the repeated application of an algorithm. Recursive Subroutine is a type of subroutine that calls itself as part of it
    7 min read
  • Perl | References
    In Perl, we use variables to access data stored in a memory location(all data and functions are stored in memory). Variables are assigned with data values that are used in various operations. Perl Reference is a way to access the same data but with a different variable. A reference in Perl is a scal
    4 min read
  • Perl | Passing Complex Parameters to a Subroutine
    Prerequisite: Perl | Subroutines or Functions A Perl function or subroutine is a group of statements that together perform a specific task. In every programming language, the user wants to reuse the code. So the user puts the section of code in a function or subroutine so that there will be no need
    4 min read
  • Perl | Pass By Reference
    When a variable is passed by reference function operates on original data in the function. Passing by reference allows the function to change the original value of a variable. When the values of the elements in the argument arrays @_ are changed, the values of the corresponding arguments will also c
    2 min read
  • Perl | Multiple Subroutines
    Prerequisite: Perl | Subroutines or Functions A Perl function or subroutine is a group of statements that together perform a specific task. In every programming language user want to reuse the code. So the user puts the section of code in function or subroutine so that there will be no need to write
    3 min read
  • Perl - Difference between Functions and Subroutines
    In Perl, when a code-script gets bigger in size i.e. contains hundreds of lines of code, it becomes difficult to manage such a code-script. To avoid this difficulty, Perl provides its users with the concept of Functions and subroutines. Functions and subroutines break up complex/large amounts of cod
    4 min read
  • VBA Subroutine in Excel - How to Call Sub in VBA?
    When a specified action is performed on a worksheet with the help of a collection of code known as a VBA Subroutine. It also helps to read an external file, also it can open other applications from Excel. A large piece of code can be broken into small parts so that we can manage it easily. Let's lea
    2 min read
  • Subroutines in COBOL
    Subroutines in COBOL are small programs that are compiled independently but cannot be run directly. Cobol subroutine is a small program that can be compiled independently but cannot be run directly. There are two types of COBOL  subroutines- internal subroutines and the external subroutines Call Ver
    3 min read
  • Relative References in Excel Macros
    We have two options to refer a cell in Excel VBA Absolute references and Relative references.  Default Excel records macro in Absolute mode. In this article, we learn about Relative references in Excel VBA.  We select a cell “A1”, turn on “Use Relative Reference” and record a macro to type some text
    5 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