in reply to Re: Override the open builtin globally
in thread Override the open builtin globally

if(defined($_[0])) { ...

You forgot to handle the case when $_[0] is undef, i.e. when the form open my $fh, ... is being used.

BEGIN { *CORE::GLOBAL::open = sub (*;$@) { use Symbol (); my $handle = Symbol::qualify_to_ref($_[0], scalar caller); $_[0] = $handle unless defined $_[0]; # pass up to caller if (@_ == 1) { CORE::open $handle; } elsif (@_ == 2) { CORE::open $handle, $_[1]; } elsif (@_ == 3) { if (defined $_[2]) { CORE::open $handle, $_[1], $_[2]; } else { CORE::open $handle, $_[1], undef; # special case } } else { CORE::open $handle, $_[1], $_[2], @_[3..$#_]; } }; } # sample usage: open my $fh, ">", \my $buf or die $!; print $fh "hello"; print $buf; # prints "hello"

Replies are listed 'Best First'.
Re^3: Override the open builtin globally
by Anonymous Monk on Jan 15, 2017 at 09:54 UTC
    Hi,

    Could you kindly advise about writing using dumper?

    The following open using last version:

    open(FILE,"> tmp.pm"); print FILE "blabla"; # works correctly #print FILE Dumper %tmp_hash; #works correctly print FILE Data::Dumper %tmp_hash; #fails: "Can't locate object metho +d "FILE" via package "Data::Dumper" "
    Any ideas/advises? since I would like to use specific pre defined Data::Dumper, which doesn't recognize the FILE.
      Add parentheses to disambiguate.

      Also, are you sure it shouldn't rather be

      print FILE Data::Dumper::Dumper( \%tmp_hash );

      ?

      ($q=q:Sq=~/;[c](.)(.)/;chr(-||-|5+lengthSq)`"S|oS2"`map{chr |+ord }map{substrSq`S_+|`|}3E|-|`7**2-3:)=~y+S|`+$1,++print+eval$q,q,a,

      The following open using last version: open(FILE,"> tmp.pm");

      Please remember to use three argument open, see open for details

      Also use lexicals (my $file) instead of globals (FILE)