I've written a goodly number of utilities over the years and in almost every case the core code is usually written with the output sent to STDOUT. As a long time fan of the 'tools' philosopy of K&R and 'nix in general this usually is a good solution. Except...well yes there is always an 'except' isn't there. As long as you apply the STDOUT solution one at a time, the problems are few-- but, as soon as you need to apply this to multiple input, then things get a little bit (sometimes more than a 'little') strained. As I'm facing just such a problem with my own code I thought I'd try and find a better approach with a small piece of perlish slight of hand.

To wit:
#!/perl/bin/perl # # wrap.pl -- proof of concept for wrapping a function tied to STDOUT, +such that you can tie it to whatever... use strict; no strict 'refs'; use warnings; use diagnostics; use IO::Scalar; use SelectSaver; for (map {glob $_} @ARGV) { my $s; wrapper((new IO::Scalar \$s),\&myFunction,$_); print "'$s'\n"; } sub wrapper { my $saver = new SelectSaver(shift); &{$_[0]}($_[1]); } sub myFunction { my $filename = shift; print "\$filename = '$filename'\n"; print <<'HERE'; template [name = "KeyValue"] (keyword,indent,value){ Keyword(text = "concat($keyword,' =')",indent = "$indent") value-of("$value") text(";") Newline() } HERE }

–hsm

"Never try to teach a pig to sing…it wastes your time and it annoys the pig."

Replies are listed 'Best First'.
Re: Getting a Handle on the un-rulely STDOUT
by John M. Dlugosz (Monsignor) on Jul 12, 2002 at 19:44 UTC
    Can you go on about the idea? I really don't see how putting SelectSaver in a wrapper really helps anything. Why not just use it directly?
      Nothing major, it is just that when a SelectSave object is destroyed by going out of scope, the default output handle is restored to its original state. That way I don't have to remember to do it myself-- got bit by that just a little bit ago, couldn't figure out why I wasn't getting any results sent to STDOUT! The function wrapper exists as a convient way to organize (and hide) the details like handle, function to execute and argument for the function.

      –hsm

      "Never try to teach a pig to sing…it wastes your time and it annoys the pig."