Reference to a function return

Discussion in 'Perl Misc' started by yoxoman, May 25, 2010.

  1. yoxoman

    yoxoman Guest

    Hello,

    In the expressions

    my $ref = \foo();

    or

    my $ref = \$myobj->foo

    $ref is a reference to a scalar, even if the foo function returns an
    array (in that case, $ref points to an element of array...)

    Do you know why ?


    Thanks.
    yoxoman, May 25, 2010
    #1
    1. Advertising

  2. yoxoman

    John Bokma Guest

    yoxoman <> writes:

    > Hello,
    >
    > In the expressions
    >
    > my $ref = \foo();
    >
    > or
    >
    > my $ref = \$myobj->foo
    >
    > $ref is a reference to a scalar, even if the foo function returns an
    > array (in that case, $ref points to an element of array...)
    >
    > Do you know why ?


    I guess you want:

    my $ref_to_return = [ foo() ];

    --
    John Bokma j3b

    Hacking & Hiking in Mexico - http://johnbokma.com/
    http://castleamber.com/ - Perl & Python Development
    John Bokma, May 25, 2010
    #2
    1. Advertising

  3. yoxoman

    C.DeRykus Guest

    On May 25, 12:02 pm, yoxoman <> wrote:
    > Hello,
    >
    > In the expressions
    >
    > my $ref = \foo();
    >
    > or
    >
    > my $ref = \$myobj->foo
    >
    > $ref is a reference to a scalar, even if the foo function returns an
    > array (in that case, $ref points to an element of array...)
    > Do you know why?


    That's because the members of the array are
    returned as a list. The LHS is a scalar so
    the comma operator acts on that list and the
    last member of the list gets assigned to the
    scalar.

    See: perldoc -q list
    "What is the difference between a list
    and an array?" ...

    Since \ provides a list, you might want to
    just use an array on the LHS:

    my @refs = \$myobj->foo.


    --
    Charles DeRykus
    C.DeRykus, May 26, 2010
    #3
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Ryan Mitchley
    Replies:
    2
    Views:
    372
    Ryan Mitchley
    Oct 16, 2003
  2. Seong-Kook Shin
    Replies:
    1
    Views:
    488
    Richard Bos
    Jun 18, 2004
  3. Greenhorn
    Replies:
    15
    Views:
    808
    Keith Thompson
    Mar 6, 2005
  4. Arv
    Replies:
    15
    Views:
    916
    James Kanze
    Mar 7, 2008
  5. Replies:
    4
    Views:
    542
    James Kanze
    Jul 22, 2008
Loading...

Share This Page