Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

Having to specify $_

by mt2k (Hermit)
on Dec 09, 2002 at 03:01 UTC ( #218437=perlquestion: print w/replies, xml ) Need Help??

mt2k has asked for the wisdom of the Perl Monks concerning the following question:

I've come across what is to me an odd behaviour.
I'm not sure as to whether this behaviour is related to perl or DBI, but it sure is strange. For the first time ever, I've come across a line of perl code that requires a person to place the variable $_ on the left side of an operation. (There may be others I'm not thinking of, but those make common sense if they exist.)

I found this out when rob_au gave me a code replacement option for DBI Queries. What he told me was that I could replace serveral lines of my code with only one line (thus eliminating the need for a hash). The line he produced for me turned the code into something close to the following:

my $dbh = DBI->connect( ... ); my $sth = $dbh->prepare ( ... ); $sth->execute ( @placeholders ); push @results, $_ while ($sth->fetchrow_hashref);

So that last line in the code sample is the line in question. That line of code will not work the way a person might believe. You'd think (if you think like me) that $_ is assigned the value of $sth->fetchrow_hashref everytime through the loop. It's not. Or it is, but not in the right way. To make the code work correctly, you must change it to specifically assign the return value of $sth->fetchrow_hashref to $_. So the line becomes:

push @results, $_ while ($_ = $sth->fetchrow_hashref);
What can I say? I don't quite understand the reason behind this behaviour. If anybody has a valid reason as to why, or perhaps a theory, let me know. The curiousity will soon do to me what it did to the cat :)

Replies are listed 'Best First'.
Re: Having to specify $_
by sauoq (Abbot) on Dec 09, 2002 at 03:15 UTC

    Functions do not assign to $_ by default. Consider

    sub foo { 'foo' }; foo(); print $_,"\n";
    You wouldn't expect that to print 'foo', would you? Well, the while loop doesn't make it any different. You have probably been confused by things like while (<>) {} (which works because <> assigns to $_ by default) and for (@list) {} which works because for will use $_ by default when an iteration variable isn't named.

    -sauoq
    "My two cents aren't worth a dime.";
    
Re: Having to specify $_
by dws (Chancellor) on Dec 09, 2002 at 03:08 UTC
    You'd think (if you think like me) that $_ is assigned the value of $sth->fetchrow_hashref everytime through the loop.

    I'd expect that $_ would be assigned during a for or foreach loop, but not during a while loop. Try

    push @results, $_ foreach ($sth->fetchrow_hashref());


    Update: It's possible to be mislead by   while ( <FILE> ) { ... Here, $_ does get set. But this is actually due to input operator behavior, as covered in the "I/O Operators" section in perlop.

    Props to rob_au for prodding this clarification.

      I'd expect that $_ would be assigned during a for or foreach loop, but not during a while loop. Try
      push @results, $_ foreach ($sth->fetchrow_hashref());

      That will only work if the function actually returns a list (and in this case it doesn't.) It will not call the function repeatedly until it returns false.

      -sauoq
      "My two cents aren't worth a dime.";
      
Re: Having to specify $_
by runrig (Abbot) on Dec 09, 2002 at 04:26 UTC
    Well, you could say:
    { push @results, $sth->fetchrow_hashref || last; redo; }
    But I think you'd be better off with a fetchall_arrayref or selectall_arrayref:
    @results = @{$sth->fetchall_arrayref({})};
    Update: Had a pop after the first bit of code. Didn't need it (it was a mistake since the last push pushes an empty list).

    Another update: That first example is deprecated. From the DBI docs on fetchrow_hashref:

    Currently, a new hash reference is returned for each row. This will change in the future to return the same hash ref each time, so don't rely on the current behaviour.
Re: Having to specify $_
by pg (Canon) on Dec 09, 2002 at 06:11 UTC
    1. $_ is also called $ARG if you 'use English;', what does the three letters 'ARG' mean? It means there are certain functions/operations, if you omit the arg, Perl will take $ARG as the default arg. In perlvar/$_, there is a complete list on this.

    2. $_ is also the place to store values, under specified situations. One example is, as stated in perlvar/$_:

      "The default place to put an input record when a <FH> operation's result is tested by itself as the sole criterion of a while test. Outside a while test, this will not happen."
    Simple, that's it. Document, and again document. Perl does deliver what perlvar promised, but not those it never promised.
Re: Having to specify $_
by Aristotle (Chancellor) on Dec 09, 2002 at 09:36 UTC
    sub collect (&@) { collect( $_[0]->() || return @_[1 .. $#_] ) } my @results = collect { $sth->fetchrow_hashref };

    :^)

    Of course, what you really want to do is use one of the fetchall methods - if your result matrices are typically large, the function call overhead for repeated fetchrows is significant.

    Update: I can't believe noone called me on my massive stupidity. Anyway, this one will actually work. (Ampersand call form is intended.)

    sub collect (&) { ($_[0]->() || return), &collect; } my @results = collect { $sth->fetchrow_hashref };

    Makeshifts last the longest.

Re: Having to specify $_
by Juerd (Abbot) on Dec 10, 2002 at 17:30 UTC

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://218437]
Approved by dws
Front-paged by diotalevi
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (2)
As of 2022-08-14 00:36 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?