Tied filehandles call a user-defined object whenever you read from or write to a filehandle, as shown in Table 9.4. Note that the tie statement takes a typeglob, not a bareword.
When you say: | Perl translates it to: |
---|---|
tie *FH, 'Foo', 'a','b' | $obj = Foo->TIEHANDLE('a','b'); |
<FH> | $obj->READLINE(); |
read (FH, $buf, $len, $offset) sysread (FH, $buf, $len, $offset) | $obj->READ($buf, $len, $offset) |
getc(FH) | $obj->GETC() |
print FH "I do"; #No comma after FH | $obj->PRINT("I do"); |
untie *FH; | $obj->DESTROY(); |
This method can be used to simulate a file or process with a test driver or to monitor access to a filehandle for silently logging a conversation (like the tee(1) command). Tk, which we will study in detail in Chapter 14, User Interfaces with Tk, supports ties to let you redirect I/O to its text widget. We will look at a small example of this feature when we study that widget.