What is the meaning of @_ in Perl?
Asked Answered
J

9

111

What is the meaning of @_ in Perl?

Joannejoannes answered 30/12, 2010 at 14:42 Comment(0)
J
128

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.

Jaf answered 30/12, 2010 at 14:47 Comment(1)
Thanks, I've only recently accustomed myself to checking perldoc, and I've found the webpages useful: 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.Brewster
A
29

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.

Accuracy answered 30/12, 2010 at 14:50 Comment(3)
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 parametersFranklin
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.Brewster
Thats it simply, and clearly understood.Marcy
N
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.

Narcosynthesis answered 30/12, 2010 at 14:44 Comment(9)
Actually the first hit of your Google search now links to this very page.Fader
...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.Narcosynthesis
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.Fader
I disagree. "Search for your problem before asking a question" is still step 0. 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.Narcosynthesis
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.Fader
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.Narcosynthesis
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.Narcosynthesis
all these "google it" answers have aged so badly 😂Axial
@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).Narcosynthesis
U
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.

Underclay answered 30/12, 2010 at 21:55 Comment(0)
H
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.

Hasa answered 30/12, 2010 at 15:54 Comment(1)
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.Hasa
L
5

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

Lunarian answered 30/12, 2010 at 14:47 Comment(0)
S
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 @_.

Slr answered 18/7, 2013 at 16:49 Comment(0)
F
2

@ 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.

Floss answered 22/2, 2014 at 17:31 Comment(1)
You should always use strict. I edited your sub function therefore.Designedly
B
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.

Bestir answered 19/9, 2017 at 15:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.