Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

set context for method's return values

by demoralizer (Beadle)
on Jan 25, 2022 at 06:42 UTC ( [id://11140834]=perlquestion: print w/replies, xml ) Need Help??

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

Hi folks,

I wonder if it is possible to use a method's return value as an array without pre-storing it into one.
This is what I really want to do:
print(split(",", "A,B,C,D")[2]);

Only solution I found (without storing the values into an array), was:
print([split(",", "A,B,C,D")]->[2]);

Is there a common perl-ish way how one can "set" the context for method's return values?

Thanks a lot in advance for all your wisdom!

Replies are listed 'Best First'.
Re: set context for method's return values
by AlexP (Pilgrim) on Jan 25, 2022 at 06:51 UTC

    I think you just need to correctly place the brackets:

    print((split(",", "A,B,C,D"))[2]);
Re: set context for method's return values
by Discipulus (Canon) on Jan 25, 2022 at 08:26 UTC
    Hello demoralizer,

    you can also:  print +(split /,/, 'A,B,C,D')[2]

    where the + sign avoid the warning print (...) interpreted as function

    > return value as an array ..

    Technically using () we are creating a list, not an array: we can access the Nth element but, for example, we cannot push to it.

    L*

    PS the phrase about parens was related to this usage, not their general use; see below..

    There are no rules, there are no thumbs..
    Reinvent the wheel, then learn The Wheel; may be one day you reinvent one of THE WHEELS.
      > Technically using () we are creating a list,

      Sorry that's not fully correct, ()[] resp. (EXPR)[SLICE] is "creating a list"

      (EXPR) alone affects only precedence, no list context is propagated.

      for completeness:

      • () is an empty list
      • (EXPR)= is a list assignment

      Cheers Rolf
      (addicted to the Perl Programming Language :)
      Wikisyntax for the Monastery

      Every once in a while I see that plus sign you used to suppress warnings, but so far I haven't been able to find an explanation for it.
      Do you have any keywords for me to search for to dig a little deeper into this topic, please?

        Not exactly sure but "unary plus" might get you on the right track. Basically the plus doesn't change the value but tells the parser after it's seen print that the next parens it sees aren't for it ("I am altering the parse tree. Pray I don't alter it further." — Darth Syntaxus).

        The cake is a lie.
        The cake is a lie.
        The cake is a lie.

        The explanation of +( is in the first section of the documentation of print.
        Be careful not to follow the print keyword with a left parenthesis unless you want the corresponding right parenthesis to terminate the arguments to the print; put parentheses around all arguments (or interpose a +, but that doesn't look as good).
        Bill
        I have to admit that it confused me for a long time too.

        I thought it's akin to 0+ which enforces scalar context and numeric casting (also in other languages like JS).

        But it's basically a No-OP which separates a function from the parens, such that the parens are not interpreted as part of the function call.

        It has sufficiently low precedence and doesn't meddle with context:

        DB<9> say ("a".."c")[1] syntax error at (eval 18)[c:/Strawberry/perl/lib/perl5db.pl:738] line +2, near ")[" DB<10> say (("a".."c")[1]) # how it works b DB<11> say +("a".."c")[1] # avoid extra parens b DB<12> say +("a".."c")[1..2] # LIST uneffected bc DB<13>

        Cheers Rolf
        (addicted to the Perl Programming Language :)
        Wikisyntax for the Monastery

Re: set context for method's return values
by haukex (Archbishop) on Jan 25, 2022 at 06:51 UTC

    You were close: print( (split(",", "A,B,C,D"))[2] )

    Nitpick: split is not a method, methods are called with ->.

      So close yet so far ;)

      Thanks to ALL of you for your helpful answers!
Re: set context for method's return values
by Marshall (Canon) on Jan 27, 2022 at 04:09 UTC
    Your code:
    print(split(",", "A,B,C,D")[2]);
    Yields:
    syntax error at XXX.pl line YYY, near ")["
    I think what you want is:
    print "",(split(",", "A,B,C,D"))[2];
    print can take a file handle as an optional arg and this can be confusing.
    putting a dummy null string in front disambiguates this. The split creates a list, put the list into paren and use the bracketed 2 to get C.

    Basically don't put a Perl variable or a function call immediately after the keyword "print". Adding more parens is a possible solution, but I prefer the above. Mileage varies.

Re: set context for method's return values
by rsFalse (Chaplain) on Jan 29, 2022 at 12:39 UTC
    You are asking for elements of the list with ()[] construction. Your list generating function may have its own parentheses depending of your preferred coding style: f( list_of_operands ) vs. f list_of_operands. Later I call more perlish.
    In both cases if you need to apply one more function, you need either one more pair of parentheses (using former function writing style), either no-op '+' symbol before an opening paren which helps parser.
    Discipulus showed a code written with second style, saving two pairs of parentheses (Re: set context for method's return values).

    Also be aware of one more known perl bug: why does 'print ("hey)")' give a warning?

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others having a coffee break in the Monastery: (4)
As of 2024-04-19 21:23 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found