Home > Blockchain >  Can you tie() a filehandle without a bareword glob?
Can you tie() a filehandle without a bareword glob?

Time:06-08

I'm trying to use Device::SerialPort without a bareword glob, see questions at the bottom.

Here is their example:

$PortObj = tie (*FH, 'Device::SerialPort', $Configuration_File_Name)
print FH "text";

... but polluting the namespace with *FH feels dirty...

I tried tie(my $fh, ...) as you would with open (my $fh, ...) but Device::SerialPort doesn't implement TIESCALAR so it gives an error.

This is my dirty hack, but it still uses a bareword and I cant even get it to scope the bareword glob:


# This does _not_ scope *FH, but shouldn't it?
{
        $port = tie(*FH, 'Device::SerialPort', $ARGV[0]) or die "$ARGV[0]: $!";
        $fh = \*FH;                      # as a GLOB
        $fh = bless(\*FH, 'IO::Handle'); # or as an IO::Handle
}

print $fh "text"; # this works

print FH "text";  # so does this, but shouldn't *FH be scoped?

Questions:

  1. Is it possible to tie in a way that does not create a bareword glob?
  2. Why do the braces not scope *fh?

CodePudding user response:

You can use local.

And I expect this to work too:

use Symbol qw( gensym );

my $fh = gensym;
tie *$fh, ...
  • Related