in reply to Re: Using Data::Dumper to dump an array of hashes to a file
in thread Using Data::Dumper to dump an array of hashes to a file

sub in { my ( $file ) = @_; open my $fh, '<', $file or die "Can't read '$file': $!"; local $/ = undef; # read whole file my $dumped = <$fh>; close $fh or die "Can't close '$file': $!"; return @{ eval $dumped }; }

Wouldn't do or require accomplish just the same task, but more succinctly?

Replies are listed 'Best First'.
Re^3: Using Data::Dumper to dump an array of hashes to a file
by kyle (Abbot) on Aug 15, 2008 at 01:21 UTC

    Mostly, yes.

    I wouldn't use require because it would decline to load the same file twice (unless you monkey with %INC). Also, I don't know if it would return the value returned by the file (I think it doesn't).

    Using do is a better choice, but the error handling is different. Here's some code I wrote a while back after examining the docs for a while:

    if ( ! defined do $rc_file ) { die "Error in '$rc_file': $@" if $@; die "Can't read '$rc_file': $!" if $!; warn "'$rc_file' returned undef as last value"; }

    It's not as easy as just "return @{ do $file }", but I admit I like it better. Using do has some other differences noted by the documentation, but nothing I'd expect to trip us up in this case.

      I wouldn't use require because it would decline to load the same file twice (unless you monkey with %INC). Also, I don't know if it would return the value returned by the file (I think it doesn't).

      It actually does :)

      I've been using require for a while to read simple config files: it does syntax error checking and the fact that it only loads once was not a big deal. However, I agree that YAML (or Config::IniFiles et al.) are safer and should be preferred.