in reply to redirecting function output

This is what local is for IMO. I hear a lot of people groan/make fun of local but it's superb for this usage. If you declare local anything and assign to it within a block, it returns to its former global assignment after the block exits. The assignment holds through the entire calling stack within a block.

use IO::File;

sub stdout_func
{
    print "Hello world.\n";
}

stdout_func();    # To STDOUT

# To /tmp/foo.out
{
    my $fh = IO::File->new(">/tmp/foo.out");
    local *STDOUT = $fh;
    stdout_func();
}

# Walla -- back to STDOUT
stdout_func();    # To STDOUT

Replies are listed 'Best First'.
Re: Re: redirecting function output
by hotshot (Prior) on Dec 17, 2001 at 12:20 UTC
    I forgot to mention that I want STDERR too to be directed to the same file, can I dup it inside the local block?

    Hotshot