Home Switchboard Unix Administration Red Hat TCP/IP Networks Neoliberalism Toxic Managers
May the source be with you, but remember the KISS principle ;-)
Bigger doesn't imply better. Bigger often is a sign of obesity, of lost control, of overcomplexity, of cancerous cells

Introduction to Perl 5.10 for Unix System Administrators

(Perl 5.10 without excessive complexity)

by Dr Nikolai Bezroukov

Contents : Foreword : Ch01 : Ch02 : Ch03 : Ch04 : Ch05 : Ch06 : Ch07 : Ch08 :

Prev | Up | Contents | Down | Next

References in Perl

version 0.85


Scripting languages usually do not contain the concept of pointers (aka references). But Perl is an exclusion from this rule and surprisingly it proved that this concept is extremely, amazingly useful even for the class of very high languages that Perl belongs to. Actually Perl proved that references are fundamental notion in programming language and exclusion of them from the scripting language leads to substantial losses of expressive power and flexibility that are far greater then dangers connected with their misuse.

Initially Perl has very limited implementation of concept of references. Perl 4 permits only symbolic references (globs). For example, in Perl 4, you have to use names to index to an associative array called _main{} of symbol names for a package. Perl 5 introduced "hard references" in true C-style. This was done to solve several recurrent problems with the language:

Although references were "bolted-on" they proved to be extremely well designed and the way they were introduced in Perl 5 did provide the capability to create complex data structures like multidimensional arrays and nested hashes.

Perl 5 also allows references to subroutines. That makes subroutines more like a regular data type. This capability proved to be useful for extension of Perl with OO programming constructs.

Review of literature

Read perllol manual page along with perlref; it discusses lists of lists and multidimensional arrays in detail. After that, you should read the perldsc manual page; it's a Data Structure Cookbook that contains recipes for using and printing out arrays of hashes, hashes of arrays, and other kinds of data.

Chapter 9 from Programming Perl, Third Edition is available on O'Reilly site:

There are several free ebooks that contain chapters about references.

In addition to consulting Perl man pages and books it makes sense to look at the Perl source code for standard modules more information. Also the 't/op' directory in the Perl source tree has regression tests that should definitely get you thinking.

Some useful documents and informative posts are available at the Web sites and PerlMonks

Top Visited
Past week
Past month


Old News ;-)

[Nov 16, 2017] perl - Passing an inner array to a function - Stack Overflow

Nov 16, 2017 |


There are no arrays in your code. And there are no method calls in your code.

Your hash is defined incorrectly. You cannot embed hashes inside other hashes. You need to use hash references. Like this:

my %data = (
    'a' => {
        x => 'Hello',
        y => 'World'
    'b' => {
        x => 'Foo',
        y => 'Bar'

Note, I'm using { ... } to define your inner hashes, not ( ... ) .

That still gives us an error though.

Type of arg 1 to main::p must be hash (not hash element) at passhash line 20, near "})"

If that's unclear, we can always try adding use diagnostics to get more details of the error:

(F) This function requires the argument in that position to be of a certain type. Arrays must be @NAME or @{EXPR}. Hashes must be %NAME or %{EXPR}. No implicit dereferencing is allowed--use the {EXPR} forms as an explicit dereference. See perlref.

Parameter type definitions come from prototypes. Your prototype is \% . People often think that means a hash reference. It doesn't. It means, "give me a real hash in this position and I'll take a reference to it and pass that reference to the subroutine".

(See, this is why people say that prototypes shouldn't be used in Perl - they often don't do what you think they do.)

You're not passing a hash. You're passing a hash reference. You can fix it by dereferencing the hash in the subroutine call.


But that's a really silly idea. Take a hash reference and turn it into a hash, so that Perl can take its reference to pass it into a subroutine.

What you really want to do is to change the prototype to just $ so the subroutine accepts a hash reference. You can then check that you have a hash reference using ref .

But that's still overkill. People advise against using Perl prototypes for very good reasons. Just remove it

> ,

Your definition of the structure is wrong. Inner hashes need to use {} , not () .
my %data = (
    a => {
        x => 'Hello',
        y => 'World'
    b => {
        x => 'Foo',
        y => 'Bar'

Also, to get a single hash element, use $data{'a'} (or even $data{a} ), not %data{'a'} .

Moreover, see Why are Perl 5's function prototypes bad? on why not to use prototypes. After correcting the syntax as above, the code works even without the prototype. If you really need the prototype, use % , not \% . But you clearly don't know exactly what purpose prototypes serve, so don't use them.

[Nov 16, 2017] perl get reference to temp list returned by function without making a copy - Stack Overflow

Nov 16, 2017 |

newguy, 2 days ago

I have a function in perl that returns a list. It is my understanding that when foo() is assigned to list a copy is made:
sub foo() { return `ping` }

my @list = foo();

That @list then needs to be transferred to another list like @oldlist = @list; and another copy is made. So I was thinking can I just make a reference from the returned list like my $listref = \foo(); and then I can assign that reference, but that doesn't work.

The function I'm working with runs a command that returns a pretty big list (the ping command is just for example purposes) and I have call it often so I want to minimize the copies if possible. what is a good way to deal with that?

zdim ,2 days ago

Make an anonymous array reference of the list that is returned
my $listref = [ foo() ];

But, can you not return an arrayref to start with? That is better in general, too.

What you attempted "takes a reference of a list" ... what one cannot do in the literal sense; lists are "elusive" things , while a reference can be taken

By using the backslash operator on a variable, subroutine, or value.

and a "list" isn't either (with a subroutine we need syntax \&sub_name )

However, with the \ operator a reference is taken, either to all elements of the list if in list context

my @ref_of_LIST = \( 1,2,3 );  #-->  @ref_of_LIST: (\1, \2, \3)

or to a scalar if in scalar context, which is what happens in your attempt. Since your sub returns a list of values, they are evaluated by the comma operator and discarded, one by one, until the last one. The reference is then taken of that scalar

my $ref_of_LIST = \( 1,2,3 );  #--> $ref_of_LIST: \3

As it happens, all this applies without parens as well, with \foo() .

newguy ,2 days ago

I don't know how to return an array ref from a command that returns a list. Would it be acceptable to do it as return [`ping`];newguy 2 days ago

zdim ,2 days ago

@newguy Yes, that would be a fine way to do it. Another is to store the command's return in an array variable (say, @ary ) -- if you need it elsewhere in the sub -- and then return \@ary;zdim 2 days ago

newguy ,2 days ago

Ok thanks. Wouldn't the @ary way create a copy though – newguy 2 days ago

zdim ,2 days ago

@newguy For one, those elements must be stored somewhere, either anonymously by [ .. ] or associated with a named variable by @ary = .. . I don't know whether yet an extra copy is made in order to construct an array, but I'd expect that it isn't When you return \@ary no new copies are made. I would expect that they are about the same. – zdim 2 days ago

zdim ,2 days ago

@newguy I added an explanation of what happens with \foo()zdim 2 days ago

[Oct 31, 2017] Perl references explained by Tom Ryder

Jan 27, 2012 |

Coming to Perl from PHP can be confusing because of the apparently similar and yet quite different ways the two languages use the $ identifier as a variable prefix. If you're accustomed to PHP, you'll be used to declaring variables of various types, using the $ prefix each time:

$string = "string";
$integer = 6;
$float = 1.337;
$object = new Object();

So when you begin working in Perl, you're lulled into a false sense of security because it looks like you can do the same thing with any kind of data:

my $string = "string";
my $integer = 6;
my $float = 1.337;
my $object = Object->new();

But then you start dealing with arrays and hashes, and suddenly everything stops working the way you expect. Consider this snippet:

my $array = (1, 2, 3);
print $array. "\n";

That's perfectly valid syntax. However, when you run it, expecting to see all your elements or at least an Array like in PHP, you get the output of "3". Not being able to assign a list to a scalar, Perl just gives you the last item of the list instead. You sit there confused, wondering how on earth Perl could think that's what you meant.

References in PHP

In PHP, every identifier is a reference, or pointer, towards some underlying data. PHP handles the memory management for you. When you declare an object, PHP writes the data into memory, and puts into the variable you define a reference to that data. The variable is not the data itself, it's just a pointer to it. To oversimplify things a bit, what's actually stored in your $variable is an address in memory, and not a sequence of data.

When PHP manages all this for you and you're writing basic programs, you don't really notice, because any time you actually use the value it gets dereferenced implicitly, meaning that PHP will use the data that the variable points to. So when you write something like:

$string = "string";
print $string;

The output you get is "string", and not "0x00abf0a9", which might be the "real" value of $string as an address in memory. In this way, PHP is kind of coddling you a bit. In fact, if you actually want two identifiers to point to the same piece of data rather than making a copy in memory, you have to use a special reference syntax:

$string2 = &$string1;

Perl and C programmers aren't quite as timid about hiding references, because being able to manipulate them a bit more directly turns out to be very useful for writing quick, clean code, in particular for conserving memory and dealing with state intelligently.

References in Perl

In Perl, you have three basic data types; scalars arrays , and hashes . These all use different identifiers; Scalars use $ , arrays use @ , and hashes use % .

my $string = "string";
my $integer = 0;
my $float = 0.0;
my @array = (1,2,3);
my %hash = (name => "Tom Ryder",
            blog => "Arabesque");

So scalars can refer directly to data in the way you're accustomed to in PHP, but they can also be references to any other kind of data. For example, you could write:

my $string = "string";
my $copy = $string;
my $reference = \$string;

The value of both $string and $copy , when printed, will be "string", as you might expect. However, the $reference scalar becomes a reference to the data stored in $string , and when printed out would give something like SCALAR(0x2160718) . Similarly, you can define a scalar as a reference to an array or hash:

my @array = (1,2,3);
my $arrayref = \@array;
my %hash = (name => "Tom Ryder",
            blog => "Arabesque");
my $hashref = \%hash;

There are even shorthands for doing this, if you want to declare a reference and the data it references inline. For array references, you use square brackets, and for hash references, curly brackets:

$arrayref = [1,2,3];
$hashref = {name => "Tom Ryder",
            blog => "Arabesque"};

And if you really do want to operate with the data of the reference, rather than the reference itself, you can explicitly dereference it:

$string = ${$reference};
@array = @{$arrayref};
%hash = %{$hashref};

For a much more in-depth discussion of how references work in Perl and their general usefulness, check out perlref in the Perl documentation.

Recommended Links

Google matched content

Softpanorama Recommended

Top articles




Groupthink : Two Party System as Polyarchy : Corruption of Regulators : Bureaucracies : Understanding Micromanagers and Control Freaks : Toxic Managers :   Harvard Mafia : Diplomatic Communication : Surviving a Bad Performance Review : Insufficient Retirement Funds as Immanent Problem of Neoliberal Regime : PseudoScience : Who Rules America : Neoliberalism  : The Iron Law of Oligarchy : Libertarian Philosophy


War and Peace : Skeptical Finance : John Kenneth Galbraith :Talleyrand : Oscar Wilde : Otto Von Bismarck : Keynes : George Carlin : Skeptics : Propaganda  : SE quotes : Language Design and Programming Quotes : Random IT-related quotesSomerset Maugham : Marcus Aurelius : Kurt Vonnegut : Eric Hoffer : Winston Churchill : Napoleon Bonaparte : Ambrose BierceBernard Shaw : Mark Twain Quotes


Vol 25, No.12 (December, 2013) Rational Fools vs. Efficient Crooks The efficient markets hypothesis : Political Skeptic Bulletin, 2013 : Unemployment Bulletin, 2010 :  Vol 23, No.10 (October, 2011) An observation about corporate security departments : Slightly Skeptical Euromaydan Chronicles, June 2014 : Greenspan legacy bulletin, 2008 : Vol 25, No.10 (October, 2013) Cryptolocker Trojan (Win32/Crilock.A) : Vol 25, No.08 (August, 2013) Cloud providers as intelligence collection hubs : Financial Humor Bulletin, 2010 : Inequality Bulletin, 2009 : Financial Humor Bulletin, 2008 : Copyleft Problems Bulletin, 2004 : Financial Humor Bulletin, 2011 : Energy Bulletin, 2010 : Malware Protection Bulletin, 2010 : Vol 26, No.1 (January, 2013) Object-Oriented Cult : Political Skeptic Bulletin, 2011 : Vol 23, No.11 (November, 2011) Softpanorama classification of sysadmin horror stories : Vol 25, No.05 (May, 2013) Corporate bullshit as a communication method  : Vol 25, No.06 (June, 2013) A Note on the Relationship of Brooks Law and Conway Law


Fifty glorious years (1950-2000): the triumph of the US computer engineering : Donald Knuth : TAoCP and its Influence of Computer Science : Richard Stallman : Linus Torvalds  : Larry Wall  : John K. Ousterhout : CTSS : Multix OS Unix History : Unix shell history : VI editor : History of pipes concept : Solaris : MS DOSProgramming Languages History : PL/1 : Simula 67 : C : History of GCC developmentScripting Languages : Perl history   : OS History : Mail : DNS : SSH : CPU Instruction Sets : SPARC systems 1987-2006 : Norton Commander : Norton Utilities : Norton Ghost : Frontpage history : Malware Defense History : GNU Screen : OSS early history

Classic books:

The Peter Principle : Parkinson Law : 1984 : The Mythical Man-MonthHow to Solve It by George Polya : The Art of Computer Programming : The Elements of Programming Style : The Unix Haterís Handbook : The Jargon file : The True Believer : Programming Pearls : The Good Soldier Svejk : The Power Elite

Most popular humor pages:

Manifest of the Softpanorama IT Slacker Society : Ten Commandments of the IT Slackers Society : Computer Humor Collection : BSD Logo Story : The Cuckoo's Egg : IT Slang : C++ Humor : ARE YOU A BBS ADDICT? : The Perl Purity Test : Object oriented programmers of all nations : Financial Humor : Financial Humor Bulletin, 2008 : Financial Humor Bulletin, 2010 : The Most Comprehensive Collection of Editor-related Humor : Programming Language Humor : Goldman Sachs related humor : Greenspan humor : C Humor : Scripting Humor : Real Programmers Humor : Web Humor : GPL-related Humor : OFM Humor : Politically Incorrect Humor : IDS Humor : "Linux Sucks" Humor : Russian Musical Humor : Best Russian Programmer Humor : Microsoft plans to buy Catholic Church : Richard Stallman Related Humor : Admin Humor : Perl-related Humor : Linus Torvalds Related humor : PseudoScience Related Humor : Networking Humor : Shell Humor : Financial Humor Bulletin, 2011 : Financial Humor Bulletin, 2012 : Financial Humor Bulletin, 2013 : Java Humor : Software Engineering Humor : Sun Solaris Related Humor : Education Humor : IBM Humor : Assembler-related Humor : VIM Humor : Computer Viruses Humor : Bright tomorrow is rescheduled to a day after tomorrow : Classic Computer Humor

The Last but not Least Technology is dominated by two types of people: those who understand what they do not manage and those who manage what they do not understand ~Archibald Putt. Ph.D

Copyright © 1996-2018 by Dr. Nikolai Bezroukov. was initially created as a service to the (now defunct) UN Sustainable Development Networking Programme (SDNP) in the author free time and without any remuneration. This document is an industrial compilation designed and created exclusively for educational use and is distributed under the Softpanorama Content License. Original materials copyright belong to respective owners. Quotes are made for educational purposes only in compliance with the fair use doctrine.

FAIR USE NOTICE This site contains copyrighted material the use of which has not always been specifically authorized by the copyright owner. We are making such material available to advance understanding of computer science, IT technology, economic, scientific, and social issues. We believe this constitutes a 'fair use' of any such copyrighted material as provided by section 107 of the US Copyright Law according to which such material can be distributed without profit exclusively for research and educational purposes.

This is a Spartan WHYFF (We Help You For Free) site written by people for whom English is not a native language. Grammar and spelling errors should be expected. The site contain some broken links as it develops like a living tree...

You can use PayPal to make a contribution, supporting development of this site and speed up access. In case is down you can use the at


The statements, views and opinions presented on this web page are those of the author (or referenced source) and are not endorsed by, nor do they necessarily reflect, the opinions of the author present and former employers, SDNP or any other organization the author may be associated with. We do not warrant the correctness of the information provided or its fitness for any purpose.

The site uses AdSense so you need to be aware of Google privacy policy. You you do not want to be tracked by Google please disable Javascript for this site. This site is perfectly usable without Javascript.

Last modified: December, 26, 2017