http://www.perlmonks.org?node_id=839787

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

hi just wanna ask is it possible for perl to get the value of a print command? for ex.

my $result = print "hello world\n"; print "$result\n";

why is it that the "print $result" would print a value which is 1?.. is it possible to get the result "hello world" not 1?... how do i do it?.. .how do i change my code? help please.

Update: tnx..u solved the problem.. this is what i really need..tnx for ur time..

Replies are listed 'Best First'.
Re: how to get value of print command
by marto (Cardinal) on May 13, 2010 at 06:59 UTC

    You're capturing the return value of the print command. If you simply want to assign a string to a variable:

    my $result = "hello world";

    Update: Please don't remove a question once you've posted it.

Re: how to get value of print command
by CountZero (Bishop) on May 13, 2010 at 07:39 UTC
    You have to do it the other way around: put the string to be printed into a variable and print the variable.

    CountZero

    A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity." - The Tao of Programming, 4.1 - Geoffrey James

Re: how to get value of print command
by jau (Hermit) on May 13, 2010 at 08:29 UTC

    Maybe this is what you want:

    #!/usr/bin/perl use strict; use warnings; close STDOUT; open( STDOUT, '>', \( my $output ) ) or die "Can't open in-memory file: $!"; print "Hello world!\n"; # prints to $output print STDERR 'STDOUT: ' . $output;

    Output:

    STDOUT: Hello world!
A reply falls below the community's threshold of quality. You may see it by logging in.