perlsignaturemethod-signature

How can I set a default file handle in a perl subroutine signature?


I have a subroutine,

use experimental "signatures";

sub foo {
  my $fh = +shift;
  open ($fh, '>', 'default_file') unless defined $fh;
}

I would like to port that to subroutine signatures. Is it possible to set $fh to default to a filehandle that points to default_file.

Something like this

sub foo ($fh=open($fh,">",foo")) {}

or even with a do{} block,

sub foo ($fh=do { open($fh,">",foo"), $fh } ) {}

I know I can get this syntax if I use or create a wrapper. But it just seems like there should be a way of some sort to get this done without invoking IO::File and the like.


Solution

  • The second attempt you showed is almost valid, you just need another variable to stand in since $fh doesn't exist yet when assigning the default; and to return it in a separate statement from where it's declared. You could abuse global variables to do this of course but that's ugly and leaky.

    sub foo ($fh=do { open(my $d,">","foo"); $d } ) {}
    

    This of course should have error handling.

    sub foo ($fh=do { open(my $d,">","foo") or die "Failed to open 'foo': $!"; $d } ) {}
    

    A proposed extension to signatures could be used to do it slightly differently, but I'm not sure if this is any better:

    sub foo (?$d, $fh=(open($d,">","foo") || die "Failed to open 'foo': $!", $d) ) {}