Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

How can I write a function's output to a scalar?

by echosilex (Acolyte)
on Jul 13, 2002 at 01:25 UTC ( [id://181432]=perlquestion: print w/replies, xml ) Need Help??

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

How can I write a function's output to a scalar?

Originally posted as a Categorized Question.

Replies are listed 'Best First'.
Re: How can I write a function's output to a scalar?
by ackohno (Scribe) on Jul 13, 2002 at 03:13 UTC
    The question is a bit vague, I assume you mean to do something like this:
    #!/usr/bin/perl -w use strict; my ($num1,$num2); $num1=2; $num2=sum($num1,$num1); print "$num2\n"; # Sum: returns the sum of all arguments. sub sum { my $ret; $ret=0; for(@_){$ret+=$_} return $ret; }
    return tells perl what the subroutine should give back when called, so $num2 is given the final value of $ret in the subroutine sum.
Re: How can I write a function's output to a scalar?
by runrig (Abbot) on Jul 13, 2002 at 05:43 UTC
    Do you mean if the function print's to STDOUT? You could maybe use local to temporarily turn STDOUT into a tied IO::Scalar filehandle...haven't tried it myself but worth a try.
Re: How can I write a function's output to a scalar?
by Abigail-II (Bishop) on Jul 16, 2002 at 14:39 UTC
    You can do it with a pipe-open, as described in man perlipc.
    #!/usr/bin/perl use strict; use warnings 'all'; sub my_function { # Does a lot, then writes print "Foobar!"; } my $pid = open my $kid => "-|"; die "Failed to fork: $!\n" unless defined $pid; unless ($pid) { my_function; exit; } my $result; { local $/; $result = <$kid>; close $kid or die "Failed to close pipe: $!\n"; } print "Got: $result\n";

    Abigail

Re: How can I write a function's output to a scalar?
by Abstraction (Friar) on Jul 16, 2002 at 14:01 UTC
    As a general rule functions should always return a value not print that value out. Following this rule will avoid problems like this.

    But if you don't have the option of modifying the function you'll have to do some trickery with STDOUT.

Log In?
Username:
Password:

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

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

    No recent polls found