in reply to use subs

This almost certainly has to do with the subtle difference between an array and a list... Which is wonderfully explained by tilly in Arrays are not lists.

Replies are listed 'Best First'.
Re: Re: use subs
by Mr. Muskrat (Canon) on Jan 24, 2003 at 15:48 UTC
    I had a nice version that would check the number of parameters passed and call CORE::open with the correct number of parameters but after reading Arrays are not lists I realized that I could shorten it greatly by using @_[0..$#_]. Thanks tilly++ (where ever you are) for writing such a great node. Thanks Gilimanjaro++ for pointing it out.
    use subs 'open'; sub open { my $params = scalar @_; print "received $params parameters...\n"; my $filehandle = shift; print "received filehandle $filehandle...\n"; print "received list @_[0..$#_]...\n"; my $return; $return = CORE::open($filehandle,@_[0..$#_]); return $return; } my $result; $result = open(TEST); print $result,$/; close(TEST); $result = open(TEST, "test.txt"); print $result,$/; close(TEST); $result = open(TEST, "<test.txt"); print $result,$/; close(TEST); $result = open(TEST, "<", "test.txt"); print $result,$/; close(TEST);
    I have left all the print statements in there for debugging purposes.
      Did I miss something (upd.: yes, I did) or couldn't this be cut down to simply:
      use subs 'open'; sub open { print @_ . "parameters: @_\n"; CORE::open(@_[0..$#_]); }
      (I didn't test anything, so I may well be way off the mark.)

      Makeshifts last the longest.

        No, it can't. The CORE::open does not succeed if you do not hand it a scalar filehandle.

        use subs 'open'; sub open { print @_ . " parameters: @_\n"; my $filehandle = shift; CORE::open($filehandle,@_[0..$#_]); } sub open2 { print @_ . " parameters: @_\n"; CORE::open(@_[0..$#_]); } my $result; print "Testing open...\n"; print open(TEST),$/; print open(TEST, "test.txt"),$/; print open(TEST, "<test.txt"),$/; print open(TEST, "<", "test.txt"),$/; print $/; print "Testing open2...\n"; print open2(TEST),$/; print open2(TEST, "test.txt"),$/; print open2(TEST, "<test.txt"),$/; print open2(TEST, "<", "test.txt"),$/; print $/;

      I figured that I would update this for the benefit of anyone who comes along and decides to try it. I went with Mr. Muskrat's idea and it has worked great. Recently I had a problem handling a first arg that is an undefined scalar, for example:
      open(my $file, "<", $file);
      Again tilly came to the rescue: see anonymous filehandle for overridden open sub.

      -Joe