Contributed by echosilex
on Jul 13, 2002 at 01:25 UTC
Q&A
> subroutines
Answer: How can I write a function's output to a scalar? contributed by ackohno 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. | Answer: How can I write a function's output to a scalar? contributed by runrig 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. | Answer: How can I write a function's output to a scalar? contributed by Abigail-II 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 | Answer: How can I write a function's output to a scalar? contributed by Abstraction 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. |
Please (register and) log in if you wish to add an answer
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
Outside of code tags, you may need to use entities for some characters:
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.
|
|