Solved

Using $_

Posted on 2008-06-20
10
126 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
Comment Utility
> 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
Comment Utility
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
Comment Utility
well, the prototype () says that whatever has no arguments,
but in general, arguments are passed in @_ , not $_

see
perldoc perlsub
0
 
LVL 39

Expert Comment

by:Adam314
Comment Utility
$_ 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
Comment Utility
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
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 39

Accepted Solution

by:
Adam314 earned 500 total points
Comment Utility
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
Comment Utility
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
Comment Utility
perldoc perldata
0
 
LVL 84

Expert Comment

by:ozo
Comment Utility
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
Comment Utility
@_ is an array, hence @
$_[0] is a scalar, hence $
http://www.perlmonks.org/index.pl?node_id=861
0

Featured Post

Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

Join & Write a Comment

Suggested Solutions

There are many situations when we need to display the data in sorted order. For example: Student details by name or by rank or by total marks etc. If you are working on data driven based projects then you will use sorting techniques very frequently.…
In the distant past (last year) I hacked together a little toy that would allow a couple of Manager types to query, preview, and extract data from a number of MongoDB instances, to their tool of choice: Excel (http://dilbert.com/strips/comic/2007-08…
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…
Sending a Secure fax is easy with eFax Corporate (http://www.enterprise.efax.com). First, Just open a new email message.  In the To field, type your recipient's fax number @efaxsend.com. You can even send a secure international fax — just include t…

744 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

Need Help in Real-Time?

Connect with top rated Experts

15 Experts available now in Live!

Get 1:1 Help Now