in reply to Working with references to scalars

Try:

put_string_ref(\(get_string()));

This works for the same reason that:

@a = \($a, $b, $c);
puts three references into @a.

Hugo

Replies are listed 'Best First'.
Re: Re: Working with references to scalars
by cees (Curate) on May 09, 2003 at 02:55 UTC

    I knew I should have tried more variations. I guess I always automatically associate lists with arrays and had already excluded round brackets in my mind for that reason.

    Thanks for the answer, and I will try to keep in mind that lists are not the same as arrays...

    As a follow up to this question though, why doesn't \(&get_string) work. I guess there must be a difference between &func and func(), but I have never come across this in my readings.

      put_string_ref( \(&get_string) ); works for me.

      According to perldoc perlsub, the & is optional as are the parentheses if the subroutine has been predeclared. The & is not optional when just naming the subroutine. Nor is it optional when you do an indrect subroutine call with a subroutine name or reference using the &$subref() or &{$subref}() constructions, although the $subref->() notatation solves that problem.

        For me they work differently.

        put_string_ref( \(get_string()) ); # pass return value of get_string() put_string_ref( \(&get_string) ); # pass a coderef pointing to &get_s +tring

        I guess if we take what tye mentioned in another response, in that we don't need the brackets for this to work, then it looks like the following holds true:

        \&func # gives you a reference to a function \func() # gives you a reference to the return value of func

        and a quick test verifies this:

        sub func { "the string"; } print \&func, "\n"; # prints CODE(0x814d990) print \func(), "\n"; # prints SCALAR(0x813aa8c)

        I guess what I've learned here is that there can be a big difference between &func and func(). I used to use them interchangably, but I will be more careful from now on.

        Thanks for your help...