Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

returning scalar context from map or grep

by !unlike (Beadle)
on Apr 28, 2003 at 13:03 UTC ( [id://253667]=perlquestion: print w/replies, xml ) Need Help??

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

Hi All,
Is there a way to turn the list context returned by map and grep into a scalar context?

By that I mean I wish to have either only the first or only value returned in scalar context and not the size of the list.

I've had several stabs at it and have had no success other than using an array placeholder. If I would like to do it inline with the map/grep as it looks neater.

!unlike

I write my Perl code like how I like my sex: fast and dirty. ;)

Replies are listed 'Best First'.
Re: returning scalar context from map or grep
by robartes (Priest) on Apr 28, 2003 at 13:08 UTC
    Do you mean something like:
    my @ary=qw/dog cat gnat/; my $first=(grep {/at$/} @ary)[0]; print $first; __END__ cat

    CU
    Robartes-

      AAAARRRRGGGG!!!!!

      I tried every method I knew apart from that one!

      Thanks Robartes, it worked a treat! ;)

      !unlike

      I write my Perl code like how I like my sex: fast and dirty. ;)

Re: returning scalar context from map or grep
by Abigail-II (Bishop) on Apr 28, 2003 at 13:19 UTC
    By assigning the result of a map or grep to a scalar, you already put the map or grep into scalar context. However, that doesn't solve your problem. Your problem isn't how to place map or grep into scalar context, your problem is getting the first result of the map or grep. To get this, you must evaluate the map or grep in list context, and take the first result from that. There are various ways of doing that, I prefer:
    my ($first) = map {whatever} @array;

    Abigail

Re: returning scalar context from map or grep
by Corion (Patriarch) on Apr 28, 2003 at 13:14 UTC

    Parentheses around the arguments to my provide list context :

    perl -le "my ($first) = grep {/bar/} (qw(foo bar baz)); print $first"

    Note please, that I'm not exactly sure whether the parentheses on the left side induce the list context though - others will most likely correct me.

    perl -MHTTP::Daemon -MHTTP::Response -MLWP::Simple -e ' ; # The $d = new HTTP::Daemon and fork and getprint $d->url and exit;#spider ($c = $d->accept())->get_request(); $c->send_response( new #in the HTTP::Response(200,$_,$_,qq(Just another Perl hacker\n))); ' # web
      Note please, that I'm not exactly sure whether the parentheses on the left side induce the list context though
      That they do, the my() isa lvalue list assignment with only one element in said list.
      HTH

      _________
      broquaint

Re: returning scalar context from map or grep
by broquaint (Abbot) on Apr 28, 2003 at 13:10 UTC
    Is there a way to turn the list context returned by map and grep into a scalar context?
    Yes, by forcing scalar context or using the scalar() function, but seeing as how that's not what you want, an array slice will just have to do
    perl -le 'print +(grep /\d/, qw/foo b4r b4z quux/)[0]' b4r
    See. perldata for more info on slicing.
    HTH

    _________
    broquaint

Re: returning scalar context from map or grep
by BrowserUk (Patriarch) on Apr 28, 2003 at 13:33 UTC

    Now you know how to do it, you might think twice about whether you should do it?

    Using map or grep to retrieve a single value is just as bad as using it in a void context I think. Your still building a (potentially large) list, only to discard all but one of the values. I do it myself on occasion, so I'm not waving a big stick, but it's worth thinking about the cost when you do it.

    Actually, it may be even worse as I seem to recall that they had been 'fixed' to not bother building the return list in a void context? I could be wrong on that.


    Examine what is said, not who speaks.
    1) When a distinguished but elderly scientist states that something is possible, he is almost certainly right. When he states that something is impossible, he is very probably wrong.
    2) The only way of discovering the limits of the possible is to venture a little way past them into the impossible
    3) Any sufficiently advanced technology is indistinguishable from magic.
    Arthur C. Clarke.

      Thanks for the warning.

      However in this instance the problems you noted do not occur in my case. I'm using grep to return a list of hash keys are in the superset and not the subset of two hases. However I know that the difference in the size of the two hases will only ever be one or two key/value pairs.

      As I am only ever interested (for now) in the first element I wanted to return a scalar value so that later code didn't have to manage an array.

      If at a later date the size of the difference does increase I will reconsider my aproach to this problem.

      Cheers all.

      !unlike

      I write my Perl code like how I like my sex: fast and dirty. ;)

Re: returning scalar context from map or grep
by PodMaster (Abbot) on Apr 28, 2003 at 13:11 UTC
    `perldoc -f scalar'

    Also, everytime context is discussed, I must bring up "List" is a Four-Letter Word.


    MJD says you can't just make shit up and expect the computer to know what you mean, retardo!
    I run a Win32 PPM repository for perl 5.6x+5.8x. I take requests.
    ** The Third rule of perl club is a statement of fact: pod is sexy.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others admiring the Monastery: (6)
As of 2024-03-28 13:45 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found