in reply to issues with eval (get a variable's value)
Fact of the matter is that I never use it. Inserting normal print/warn/die statements just comes more natural after all this time. The code is essentially the first version that ran, I never bothered to clean it up. Anyway, here it is:
That printsuse Report 'report'; my ( $i, $j) = ( 42, 'freeBSD'); my %h = ( one => [ 4, 5, 6], two => 'gaga'); report qw( $i $j $h{one} $h{two} $h{three});
Here is the module Report.pm$i = 42; $j = 'freeBSD'; $h{one} = [ 4, 5, 6 ]; $h{two} = 'gaga'; $h{three} = undef;
package Report; use strict; use warnings; # @^~` use base 'Exporter'; our @EXPORT = qw( report); { # DB evaluates in caller context package DB; sub DB::_report_report { for my $expr ( @_ ) { print Report::answer( $expr, eval $expr); } } } *Report::report = \ &DB::_report_report; use Data::Dumper (); use Scalar::Util (); sub answer { my ( $expr, @val) = @_; my $ans; if ( $@ ) { $ans = "$expr: $@" if $@; $ans =~ s/ at \(eval .*$//; } else { if ( @val == 1 ) { $ans = answer_scalar( $expr, @val); } else { $ans =join ', ' => map answer_scalar( $expr, $_), @val; $ans = "($ans)"; } } $ans; } sub answer_scalar { my ( $expr, $val) = @_; my $ans; if ( !defined $val ) { $ans = "$expr = undef;\n"; } elsif ( ref $val ) { ( $ans = Data::Dumper::Dumper $val) =~ s/\$VAR1\b/$expr/g; my $indent = ' ' x ( 8 + length( $expr) - length( '$VAR')); $ans =~ s/^ {8}/$indent/mg; } elsif ( Scalar::Util::looks_like_number( $val) or ref( \ $val) eq 'GLOB' ) { $ans = "$expr = $val;\n"; } else { $ans = "$expr = '$val';\n"; } $ans; } 1;
|
|---|