Solved

Using $_

Posted on 2008-06-20
10
132 Views
Last Modified: 2010-03-05
Hi,

I know the $_ operator is some global general storage for 'stuff' in certain operations, like:

    while (<>) {
         chomp;
    }

that is reading a line from input into $_ then runs chomp() on the contents of $_.

Is $_ used to get data passed to functions? In the following:

    sub whatever()
    {
         my ($x, @y, %z) = @_;
    }

is the $_ variable being used as a temporary storage area until you extract the passed parameters in the sub routine? If not, how do they get there!


Also, I know $_ is used here:

    for (@myarray) {
        print("Current element is: ", $_, "\n");
    }

is this typical in perl, or are people more likely to explicitly do something like:

    for (my $i = 0; $i < @myarray; $i++) {
        ....
    }

Thanks

0
Comment
Question by:DJ_AM_Juicebox
  • 5
  • 3
  • 2
10 Comments
 
LVL 84

Expert Comment

by:ozo
ID: 21833698
> Is $_ used to get data passed to functions?
not unless you explicitly use it with something like
($_,@y) = @_;

>    for (@myarray)
is typical perl
> for (my $i = 0; $i < @myarray; $i++) {
might be used by someone used to C, or if $i was going to be used for other things
0
 

Author Comment

by:DJ_AM_Juicebox
ID: 21833782
Ok so in this statement:

    sub whatever()
    {
         my ($x, @y, %z) = @_;
    }

$_ is NOT used? What mechanism does perl use then to store the junk you passed the function when you called it over and into the whatever() function? Just curious.

Thanks
0
 
LVL 84

Expert Comment

by:ozo
ID: 21833842
well, the prototype () says that whatever has no arguments,
but in general, arguments are passed in @_ , not $_

see
perldoc perlsub
0
Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

 
LVL 39

Expert Comment

by:Adam314
ID: 21834164
$_ and @_ are two different variables.  The $_ is a scalar, and @_ is an array.

Also, with:
    sub whatever()
    {
         my ($x, @y, %z) = @_;
    }

The @y would take up the all of the variables left, so there would be nothing in %z.
0
 

Author Comment

by:DJ_AM_Juicebox
ID: 21834208
I'm confused - I thought a sub prototype didn't require any parameters, so you could write:


    test(5, 10);

    sub test()
    {
        my $x = $_[0];
        my $y = $_[1];
    }

and that works fine. So you're saying you could also write it like:

    sub test($$)
    {
        ..
    }

to mean it takes two scalars? You just pile the type one after another, like $@@$% means take a scalar, array, array, scalar, hash? (Not a curse word?).



Hmmm ok now about $_ from the docs:

"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] ."

So, for whatever reason, in your sub body you can access the passed parameters like:

     my ($x, $y) = @_;

OR

   my $x = $_[0];
   my $y = $_[1];

OR
 
   my $x = shift;
   my $y = shift;


but I guess all three methods must use $_ because perl isn't compiled and it will only know which method you use at run-time right, so it needs to keep that inside $_ in case you want to use the latter two methods of accessing the parameters?

Thanks
0
 
LVL 39

Accepted Solution

by:
Adam314 earned 500 total points
ID: 21834432
A prototype isn't necessary.  To declare a subroutine with a prototype, you leave off the parenthesis:
    sub test    #No parenthesis
    {
        my $x = $_[0];
        my $y = $_[1];
    }

You just pile on the type.  The problem with $@@$% for a prototype is that when parameters are passed, they are passed as a single list.  So when you are getting them back into their variables, you won't know when the second array ends and the third starts.  If you need to pass multiple arrays, you would usually use array references, with a prototype like $\@\@$\%.

For the subroutines: @_ is the array that holds all of the parameters passed to the subroutine.  It is an array.  Just like if you have an array @myArray, you access the elements like $myArray[0] and $myArray[1], you access the elements of @_ with $_[0] and $_[1].  This has nothing to do with $_, these are seperate unrelated variables.  When you use shift without any parameters, it shifts the @_ array.  So these two are exactly the same:
    my $x = shift;
    my $x = shift @_;
http://perldoc.perl.org/functions/shift.html

0
 

Author Comment

by:DJ_AM_Juicebox
ID: 21834508
For the $@@$ thing, I completely understand now, makes sense, thank you.

For the second part, I just find it so strange that they made this $_ variable which is used in for loops, regexes, etc, but then they also use the syntax $_[index] to get at the elements of @_, but the two are unrelated.

Thanks for your patience.
0
 
LVL 84

Expert Comment

by:ozo
ID: 21834542
perldoc perldata
0
 
LVL 84

Expert Comment

by:ozo
ID: 21834586
If it's not in a subroutine,
    my $x = shift;
is the same as
    my $x = shift @ARGV;
0
 
LVL 84

Expert Comment

by:ozo
ID: 21834710
@_ is an array, hence @
$_[0] is a scalar, hence $
http://www.perlmonks.org/index.pl?node_id=861
0

Featured Post

ScreenConnect 6.0 Free Trial

At ScreenConnect, partner feedback doesn't fall on deaf ears. We collected partner suggestions off of their virtual wish list and transformed them into one game-changing release: ScreenConnect 6.0. Explore all of the extras and enhancements for yourself!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Extract multiple value with delimiters from a string 4 170
perl search and replace 6 168
Perl DBI Transactions Using Custom Module 7 47
Perl Awk Need Help 3 117
I've just discovered very important differences between Windows an Unix formats in Perl,at least 5.xx.. MOST IMPORTANT: Use Unix file format while saving Your script. otherwise it will have ^M s or smth likely weird in the EOL, Then DO NOT use m…
I have been pestered over the years to produce and distribute regular data extracts, and often the request have explicitly requested the data be emailed as an Excel attachement; specifically Excel, as it appears: CSV files confuse (no Red or Green h…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
The Email Laundry PDF encryption service allows companies to send confidential encrypted  emails to anybody. The PDF document can also contain attachments that are embedded in the encrypted PDF. The password is randomly generated by The Email Laundr…

772 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question