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

Hi, I've got a subroutine that I use for printing. When called, a filehandle and stringtoprint are passed as arguments. The subroutine shifts the filehandle and string off into local vars and uses print to print the string to the filehandle. It works. However, I would like to be able to use this to print the output of a 'print Dumper' statement and I have no idea how to try to do this. Any suggestions? Examples? Thanks, bigtiny
  • Comment on passing Dumper output to print subroutine?

Replies are listed 'Best First'.
Re: passing Dumper output to print subroutine?
by AnomalousMonk (Archbishop) on Sep 09, 2010 at 19:54 UTC

    bigtiny: I think the point you are missing is that the output of the  Dumper function is already a string. As such, it can be operated with or operated on (or passed as a parameter to a function) just as any other string can be.

    >perl -wMstrict -le "use Data::Dumper; my @ra = (1, 2, { 3 => 'three' } ); my $du = Dumper \@ra; print qq{**$du**}; " **$VAR1 = [ 1, 2, { '3' => 'three' } ]; **

    Update: Changed wording, example code slightly to better make the point.

Re: passing Dumper output to print subroutine?
by TomDLux (Vicar) on Sep 09, 2010 at 16:28 UTC

    You mean something like:

    use Data::Dumper; use Fatal qw(open close); open my $log, '>', $path_to_log; my_print_routine( $log, Dumper( \%some_var ) );

    Update ... I imagine your subroutine just uses print, with no room for specifying a filehandle. Something like:

    <code> sub my_print_routine { print for @_; print "\n"; }

    You could select your filehandle to make it the default output, but that doesn't work if you also print to STDOUT. You could modify the print routine to check whether the first arg is a filehandle, and select it there, saving the previous value to select it back at the routine exit.

    P.S. Bareword fielhandles and two-argument open are so Perl4 ... check out 'perldoc -f open' for the modern way.

    Update 2 ... I dunno about others, I would check the first arg by seeing if : 'GLOB' eq ref $_[0]. if you had a valid reason for passing around GLOBs, that would fail.

    As Occam said: Entia non sunt multiplicanda praeter necessitatem.

Re: passing Dumper output to print subroutine?
by mje (Curate) on Sep 09, 2010 at 16:26 UTC

    Perhaps I misunderstand you:

    perl -le 'use Data::Dumper; open(my $fh, ">x.txt") or die "open $!"; p +rint $fh Dumper([1,2,3]);'