Title: tie
1tie
use WorkshopPerlDutch 3 date( 2006-05-17
) author( abeltje gt Abe Timmerman )
2tie()
- Bind a variable to a package to override the
access mechanism - Possible types
- Scalar
- Array
- Hash
- Handle
- Access to the underlying object with tied()
3TIESCALAR
- API
- TIESCALAR constructor
- FETCH
- STORE
- UNTIE
- DESTROY
4TIESCALAR (src1)
package Odd_Even use strict use warnings sub
TIESCALAR my class shift bless \(my
self shift), class sub FETCH my
self shift return self 2 0 ?
'even' 'odd' sub STORE my self
shift self shift 1
5TIESCALAR (src2)
! /usr/bin/perl use strict use warnings use
Odd_Even tie my oe, 'Odd_Even', 0 while ( 1 )
print "Number " chomp( my input ltgt )
last unless input oe input
printf "input is oe (d)\n, tied oe
6Demorun
scalar.pl
7TIEARRAY
- API
- TIEARRAY constructor
- FETCH, STORE
- FETCHSIZE, STORESIZE
- CLEAR, EXTEND
- EXISTS, DELETE
- PUSH, POP,
- SHIFT, UNSHIFT, SPLICE
- UNTIE, DESTROY
8TIEARRAY (src1)
package CharArray use strict use warnings sub
TIEARRAY my( pkg, init ) _at__ my
self bless \( my store ), pkg self
defined init ? init '' self sub
FETCH my( self, index ) _at__ index
gt length self and self-gtEXTEND( index )
substr self, index, 1 sub STORE my(
self, index, value ) _at__ index gt
length self and self-gtEXTEND( index )
substr self, index, 1, value sub FETCHSIZE
length _0 sub STORESIZE my(
self, size ) _at__ if ( size gt length
self ) self-gtEXTEND( size )
else self substr self, 0, size
size sub EXTEND my( self,
size ) _at__ size gt length self and
self . "\00" x ( 1 size - length
self) sub CLEAR _0 '' 1
9TIEARRAY (src2)
! /usr/bin/perl use strict use warnings use
CharArray sub print_it(\_at_) my chars
shift print "gt_at_charslt\n" for my char
( _at_chars ) print "char\n"
tie my _at_chars, 'CharArray', 'Test' print_it
_at_chars chars 2 print_it _at_chars _at_chars3,4
( 't', '!' ) print_it _at_chars
10Demorun
array.pl
11TIEHASH
- API
- TIEHASH consructor
- FETCH, STORE
- FIRSTKEY, NEXTKEY
- EXISTS, DELETE
- CLEAR, UNTIE, DESTROY
12TIEHANDLE
- API
- TIEHANDLE constructor
- writing
- PRINT, PRINTF
- WRITE
- reading
- READLINE
- READ, GETC
- CLOSE
- UNTIE, DESTROY
13TIEHANDLE (src1)
package CatchOut use strict use warnings sub
TIEHANDLE my class shift bless \(my
buf), class sub PRINT my self
shift self . join "", _at__ sub UNTIE
1
14TIEHANDLE (src2)
! /usr/bin/perl use strict use warnings use
CatchOut print "Start capturing STDOUT\n" my
out '' tie STDOUT, 'CatchOut'
print "Caught the first line.\n" print
"Caught the second line.\n" out
tied( STDOUT ) untie STDOUT print
"Lines caught from STDOUT\n", map "\t_\n" gt
split /\n/, out print "Start capturing
STDERR\n" my err '' tie STDERR,
'CatchOut' print STDERR "Cought the 1st line
from STDERR\n" warn "Cought the 2nd line
from warn()\n" err tied( STDERR )
untie STDERR print "Lines caught from
STDERR\n", map "\t_\n" gt split /\n/, err
15Demorun
outhandle.pl duphanlde.pl inhandle.pl
16QUESTIONS?
17Bonus (half windsor)