Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does '@_' do in Perl?

Tags:

variables

perl

I was glancing through some code I had written in my Perl class and I noticed this.

my ($string) = @_;
my @stringarray = split(//, $string);

I am wondering two things: The first line where the variable is in parenthesis, this is something you do when declaring more than one variable and if I removed them it would still work right?

The second question would be what does the @_ do?

like image 826
Levi Avatar asked Jan 17 '09 04:01

Levi


People also ask

What is meant by $_ in Perl?

The most commonly used special variable is $_, which contains the default input and pattern-searching string. For example, in the following lines − #!/usr/bin/perl foreach ('hickory','dickory','doc') { print $_; print "\n"; }

What does =~ mean in Perl language?

=~ is the Perl binding operator. It's generally used to apply a regular expression to a string; for instance, to test if a string matches a pattern: if ($string =~ m/pattern/) {

What is @_ in Perl script?

The @_ variable is an array that contains all the parameters passed into a subroutine. The parentheses around the $string variable are absolutely necessary. They designate that you are assigning variables from an array.


2 Answers

The @_ variable is an array that contains all the parameters passed into a subroutine.

The parentheses around the $string variable are absolutely necessary. They designate that you are assigning variables from an array. Without them, the @_ array is assigned to $string in a scalar context, which means that $string would be equal to the number of parameters passed into the subroutine. For example:

sub foo {
  my $bar = @_;
  print $bar;
}

foo('bar');

The output here is 1--definitely not what you are expecting in this case.

Alternatively, you could assign the $string variable without using the @_ array and using the shift function instead:

sub foo {
  my $bar = shift;
  print $bar;
}

Using one method over the other is quite a matter of taste. I asked this very question which you can check out if you are interested.

like image 175
cowgod Avatar answered Oct 02 '22 17:10

cowgod


When you encounter a special (or punctuation) variable in Perl, check out the perlvar documentation. It lists them all, gives you an English equivalent, and tells you what it does.

like image 39
brian d foy Avatar answered Oct 02 '22 16:10

brian d foy