108

What is the meaning of @_ in Perl?

DVK
  • 126,886
  • 32
  • 213
  • 327
Andrei
  • 1,862
  • 4
  • 15
  • 15

9 Answers9

127

perldoc perlvar is the first place to check for any special-named Perl variable info.

Quoting:

@_: Within a subroutine the array @_ contains the parameters passed to that subroutine.

More details can be found in perldoc perlsub (Perl subroutines) linked from the perlvar:

Any arguments passed in show up in the array @_ .

Therefore, if you called a function with two arguments, those would be stored in $_[0] and $_[1].

The array @_ is a local array, but its elements are aliases for the actual scalar parameters. In particular, if an element $_[0] is updated, the corresponding argument is updated (or an error occurs if it is not updatable).

If an argument is an array or hash element which did not exist when the function was called, that element is created only when (and if) it is modified or a reference to it is taken. (Some earlier versions of Perl created the element whether or not the element was assigned to.) Assigning to the whole array @_ removes that aliasing, and does not update any arguments.

cjm
  • 61,471
  • 9
  • 126
  • 175
DVK
  • 126,886
  • 32
  • 213
  • 327
  • Thanks, I've only recently accustomed myself to checking perldoc, and I've found the webpages useful: http://perldoc.perl.org/perlvar.html It wasn't bad to make a perl stub that launches this on the web...a webpage's formatting helps me a lot. – aschultz Dec 04 '16 at 07:21
28

Usually, you expand the parameters passed to a sub using the @_ variable:

sub test{
  my ($a, $b, $c) = @_;
  ...
}

# call the test sub with the parameters
test('alice', 'bob', 'charlie');

That's the way claimed to be correct by perlcritic.

Wolf
  • 9,679
  • 7
  • 62
  • 108
eckes
  • 64,417
  • 29
  • 168
  • 201
  • 2
    this is one time I disagree with `perlcritic`, personally I think that this is best for a function, but for a method, it is useful to `shift` the self reference, then unpack the `@_` array. This makes it clear that this is a method AND that the method takes certain parameters – Joel Berger May 09 '11 at 14:25
  • 1
    I probably should have used/known about PERLCritic before, but I didn't. Thanks for using it in this example. Sometimes stuff you reference offhand can help someone learn something entirely new to them. – aschultz Dec 04 '16 at 07:22
  • Thats it simply, and clearly understood. – R.G.Krish Jan 17 '23 at 10:47
13

First hit of a search for perl @_ says this:

@_ is the list of incoming parameters to a sub.

It also has a longer and more detailed explanation of the same.

daxim
  • 39,270
  • 4
  • 65
  • 132
Piskvor left the building
  • 91,498
  • 46
  • 177
  • 222
  • 5
    Actually the first hit of your Google search now links to this very page. – Gabriel Southern Aug 14 '17 at 22:14
  • ...seven *years* later, an eternity in internet time. Which is why I both linked to the first result and qouted the relevant part: depending on Google alone would be very naive. – Piskvor left the building Aug 14 '17 at 22:16
  • 1
    true it's many years later, but it's still annoying to read answer that imply that you should Google for an answer to the question. It's pointless information for someone reading the answer as a result of Googling. – Gabriel Southern Aug 14 '17 at 22:21
  • I disagree. "Search for your problem *before* asking a question" is still step 0. https://stackoverflow.com/help/how-to-ask Annoying to *you*, perhaps - but so is a bunch of repeated questions that *could* have been answered by querying the machines first. – Piskvor left the building Aug 14 '17 at 22:32
  • 2
    Yes searching is the correct first step, but it's not necessary to include instructions to search in your answer. It's redundant information that adds no value, and it's ironic because if someone follows the search link in your answer it brings them back where they started. – Gabriel Southern Aug 14 '17 at 22:49
  • Learn to live with the redundancy, then: the world is redundant and also redundant. Also, you are 1. free to suggest an edit and 2.wrong: it does *not* bring them back, because it *also* includes the correct answer, as well as its source. – Piskvor left the building Aug 14 '17 at 22:52
  • And btw, yes, SO was supposed to reduce the redundancy. Guess how well *that* went? And guess why? **Because the users could not be bothered to UTFG first, or even check whether SO already has an identical question** - the same Google search that we're arguing about now has four (4) near-identical SO answers at the top. Redundantly redundant redundancy. – Piskvor left the building Aug 14 '17 at 22:55
  • 1
    all these "google it" answers have aged so badly – Austin Adams Apr 08 '19 at 16:53
  • @AustinAdams I beg to differ. When I wrote that, 8 years ago, I was already aware that Google results change with time, thank you very much. Hence, the answer contains both the link to what was the first result *at the time*, and its gist (oh look, link rot also exists, whoa). – Piskvor left the building Apr 08 '19 at 16:57
11

The question was what @_ means in Perl. The answer to that question is that, insofar as $_ means it in Perl, @_ similarly means they.

No one seems to have mentioned this critical aspect of its meaning — as well as theirs.

They’re consequently both used as pronouns, or sometimes as topicalizers.

They typically have nominal antecedents, although not always.

tchrist
  • 78,834
  • 30
  • 123
  • 180
7

You can also use shift for individual variables in most cases:

$var1 = shift;

This is a topic in which you should research further as Perl has a number of interesting ways of accessing outside information inside your sub routine.

Anatoliy Nikolaev
  • 22,370
  • 15
  • 69
  • 68
hockfan86
  • 231
  • 1
  • 2
  • 3
    Cool, whoever gave me a down vote simply for posting another way to do a similar thing. I realize I didn't answer the question directly because someone already did, but I offered an alternative form that new perl programmers are often confused by. – hockfan86 Feb 14 '11 at 02:59
5

All Perl's "special variables" are listed in the perlvar documentation page.

aschepler
  • 70,891
  • 9
  • 107
  • 161
2

Also if a function returns an array, but the function is called without assigning its returned data to any variable like below. Here split() is called, but it is not assigned to any variable. We can access its returned data later through @_:

$str = "Mr.Bond|Chewbaaka|Spider-Man";
split(/\|/, $str);

print @_[0]; # 'Mr.Bond'

This will split the string $str and set the array @_.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Afser2000
  • 164
  • 1
  • 7
1

@ is used for an array.

In a subroutine or when you call a function in Perl, you may pass the parameter list. In that case, @_ is can be used to pass the parameter list to the function:

sub Average{

    # Get total number of arguments passed.
    $n = scalar(@_);
    $sum = 0;

    foreach $item (@_){

        # foreach is like for loop... It will access every
        # array element by an iterator
        $sum += $item;
    }

    $average = $sum / $n;

    print "Average for the given numbers: $average\n";
}

Function call

Average(10, 20, 30);

If you observe the above code, see the foreach $item(@_) line... Here it passes the input parameter.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Omar Faroque Anik
  • 2,531
  • 1
  • 29
  • 42
1

Never try to edit to @_ variable!!!! They must be not touched.. Or you get some unsuspected effect. For example...

my $size=1234;
sub sub1{
  $_[0]=500;
}
sub1 $size;

Before call sub1 $size contain 1234. But after 500(!!) So you Don't edit this value!!! You may pass two or more values and change them in subroutine and all of them will be changed! I've never seen this effect described. Programs I've seen also leave @_ array readonly. And only that you may safely pass variable don't changed internal subroutine You must always do that:

sub sub2{
  my @m=@_;
  ....
}

assign @_ to local subroutine procedure variables and next worked with them. Also in some deep recursive algorithms that returun array you may use this approach to reduce memory used for local vars. Only if return @_ array the same.

Anatoly
  • 11
  • 1