SlideShare ist ein Scribd-Unternehmen logo
1 von 19
The Magic of tie
            brian d foy
     brian@stonehenge.com
Stonehenge Consulting Ser vices
         May 26, 2006
 Dallas-Ft. Worth Perl Mongers
Fun with variables

Tied variables are really hidden objects
The objects have a hidden interface to
make them act like normal variables
Behind that interface, we do we what
Normal variables
         $value = 5;
   $other_value = $value;

    @array = qw( a b c );
       $array[3] = ‘d’;
        $last = $#array
         shift @array;

%hash = map { $_, 1 } @array;
         $hash{a} = 2;
       delete $hash{b};
    my @keys = keys %hash;
Do what we want
  The tie interface let’s us decide what to do
  in each case
  We can store values any way we like

tie my $scalar, ‘Tie::Foo’, @args;
 tie my @array, ‘Tie::Bar’, @args;
 tie my %hash, ‘Tie::Quux’, @args;
   tie my $fh, ‘Tie::Baz’, @args;
Do what the user knows

 Scalars, arrays, hashes
 Common, “Learning Perl” level syntax
 Hide all of the complexity
DBM::Deep
          Persistent hashes
use DBM::Deep;
my $db = DBM::Deep->new( quot;foo.dbquot; );

$db->{key} = 'value';
print $db->{key};

# true multi-level support
$db->{my_complex} = [
      'hello', { perl => 'rules' },
      42, 99 ];
Tie:: modules
Tie::Scalar Tie::Array Tie::Hash Tie::Handle
                    Tie::File
      Tie::Cycle Tie::Toggle Tie::FlipFlop
               Tie::Handle::CSV
                Tie::SortHash
            IO::Scalar IO::String
Two variables
The normal looking variable
and it’s secret life as an object

my $object =

 tie my $scalar,

 
 ‘Tie::ClassName’,

 
 @args;
We do this...      Perl does this...



  $scalar         $object->FETCH



$scalar = 5      $object->STORE(5)
Scalars
                                my $object =
    tie my $scalar,
                                  Tie::Foo-
  ‘Tie::Foo’, @args;
                            >TIESCALAR( @args )


    $n = $scalar;          $n = $object->FETCH;


     $scalar = 5;           $object->STORE(5);


tied($scalar)->foo(5);        $object->foo(5);



         and a few others: DESTROY, UNTIE
Tie::Cycle
use Tie::Cycle;

tie my $cycle, 'Tie::Cycle',

 
 [ qw( FFFFFF 000000 FFFF00 ) ];

print   $cycle;   #   FFFFFF
print   $cycle;   #   000000
print   $cycle;   #   FFFF00
print   $cycle;   #   FFFFFF    back to the beginning

(tied $cycle)->reset;          # back to the beginning
IO::Scalar
use 5.005;
use IO::Scalar;
$data = quot;My message:nquot;;

### Open a handle on a string
$SH = IO::Scalar->new( $data );
$SH->print(quot;Helloquot;);
$SH->print(quot;, world!nBye now!nquot;);
print quot;The string is now: quot;, $data, quot;nquot;;

                   == OR ==
    open my $fh, “>”, $variable;
Tie::Scalar


Base class for tied scalars
Override for the parts you need
Arrays
                                     my $object =
     tie my @array,
                                       Tie::Foo-
   ‘Tie::Foo’, @args;
                                  >TIEARRAY( @args )
    $n = $array[$i];          $n = $object->FETCH($i);

    $array[$i] = 5;             $object->STORE($i, 5);

       $n = @array               $object->FETCHSIZE;

      $#array = $n;           $object->STORESIZE($n+1);

     $#array += $n;              $object->EXTEND($n);

      @array = ();                  $object->CLEAR;

and a few others: DELETE, EXISTS, PUSH, POP, SHIFT, UNSHIFT,
                  SPLICE, DESTROY, UNTIE
Tie::Array


Base class for tied arrays
Override the parts you need
Hashes
                                 my $obj =
     tie my %hash,
                                 Tie::Foo-
  ‘Tie::Foo’, @args;
                             >TIEHASH( @args )
 $n = $hash{ $key };      $n = $obj->FETCH($key);
  $hash{ $key } = 5;       $obj->STORE($key, 5);
delete $hash{ $key };      $obj->DELETE( $key )

exists $hash{ $key };      $obj->EXISTS( $key )

     %hash = ();                $obj->CLEAR
                                 @keys = (
my @keys = keys %hash;        $obj->FIRSTKEY,
                            $obj->NEXTKEY ... )

     and a few others: SCALAR, UNTIE, DESTROY
Tie::Hash


Base class for tied hashes
Override the parts you need
Filehandles
                                 my $object =
      tie my $fh,
                                   Tie::Foo-
  ‘Tie::Foo’, @args;
                             >TIEHANDLE( @args )


  print $fh @stuff;        $object->PRINT(@stuff);


   my $line = <$fh>           $object->READLINE;


      close $fh;                $object->CLOSE;


and a few others: WRITE, PRINTF, READ, DESTROY, UNTIE
Tie::Handle


Base class for tied handles
Override the parts you need

Weitere ähnliche Inhalte

Was ist angesagt?

News of the Symfony2 World
News of the Symfony2 WorldNews of the Symfony2 World
News of the Symfony2 World
Fabien Potencier
 
Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)
Kang-min Liu
 

Was ist angesagt? (20)

What's New in Perl? v5.10 - v5.16
What's New in Perl?  v5.10 - v5.16What's New in Perl?  v5.10 - v5.16
What's New in Perl? v5.10 - v5.16
 
Perl5i
Perl5iPerl5i
Perl5i
 
Doctrine MongoDB ODM (PDXPHP)
Doctrine MongoDB ODM (PDXPHP)Doctrine MongoDB ODM (PDXPHP)
Doctrine MongoDB ODM (PDXPHP)
 
News of the Symfony2 World
News of the Symfony2 WorldNews of the Symfony2 World
News of the Symfony2 World
 
Perl 6 by example
Perl 6 by examplePerl 6 by example
Perl 6 by example
 
Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)Good Evils In Perl (Yapc Asia)
Good Evils In Perl (Yapc Asia)
 
Barcelona.pm Curs1211 sess01
Barcelona.pm Curs1211 sess01Barcelona.pm Curs1211 sess01
Barcelona.pm Curs1211 sess01
 
Dades i operadors
Dades i operadorsDades i operadors
Dades i operadors
 
PHP Tips & Tricks
PHP Tips & TricksPHP Tips & Tricks
PHP Tips & Tricks
 
Perl6 grammars
Perl6 grammarsPerl6 grammars
Perl6 grammars
 
Functional programming with php7
Functional programming with php7Functional programming with php7
Functional programming with php7
 
PHP PPT FILE
PHP PPT FILEPHP PPT FILE
PHP PPT FILE
 
The most exciting features of PHP 7.1
The most exciting features of PHP 7.1The most exciting features of PHP 7.1
The most exciting features of PHP 7.1
 
Electrify your code with PHP Generators
Electrify your code with PHP GeneratorsElectrify your code with PHP Generators
Electrify your code with PHP Generators
 
6 things about perl 6
6 things about perl 66 things about perl 6
6 things about perl 6
 
Nubilus Perl
Nubilus PerlNubilus Perl
Nubilus Perl
 
Perl Web Client
Perl Web ClientPerl Web Client
Perl Web Client
 
The Perl6 Type System
The Perl6 Type SystemThe Perl6 Type System
The Perl6 Type System
 
Neatly Hashing a Tree: FP tree-fold in Perl5 & Perl6
Neatly Hashing a Tree: FP tree-fold in Perl5 & Perl6Neatly Hashing a Tree: FP tree-fold in Perl5 & Perl6
Neatly Hashing a Tree: FP tree-fold in Perl5 & Perl6
 
Introdução ao Perl 6
Introdução ao Perl 6Introdução ao Perl 6
Introdução ao Perl 6
 

Andere mochten auch

Module 1 lesson 8 unit rate as constant of proportionality
Module 1 lesson 8 unit rate as constant of proportionalityModule 1 lesson 8 unit rate as constant of proportionality
Module 1 lesson 8 unit rate as constant of proportionality
Erik Tjersland
 

Andere mochten auch (20)

System Monitoring
System MonitoringSystem Monitoring
System Monitoring
 
Rupal CV (1)
Rupal CV (1)Rupal CV (1)
Rupal CV (1)
 
Why I Love CPAN
Why I Love CPANWhy I Love CPAN
Why I Love CPAN
 
Module 1 lesson 8 unit rate as constant of proportionality
Module 1 lesson 8 unit rate as constant of proportionalityModule 1 lesson 8 unit rate as constant of proportionality
Module 1 lesson 8 unit rate as constant of proportionality
 
Presentacion
PresentacionPresentacion
Presentacion
 
Concertation en faveur de l'insertion des jeunes - Séance 1
Concertation en faveur de l'insertion des jeunes - Séance 1Concertation en faveur de l'insertion des jeunes - Séance 1
Concertation en faveur de l'insertion des jeunes - Séance 1
 
Lever les freins périphériques à l'emploi des jeunes : priorités et leviers
Lever les freins périphériques à l'emploi des jeunes : priorités et leviersLever les freins périphériques à l'emploi des jeunes : priorités et leviers
Lever les freins périphériques à l'emploi des jeunes : priorités et leviers
 
EventShop Demo
EventShop DemoEventShop Demo
EventShop Demo
 
Sip report
Sip reportSip report
Sip report
 
HBaseConEast2016: Coprocessors – Uses, Abuses and Solutions
HBaseConEast2016: Coprocessors – Uses, Abuses and SolutionsHBaseConEast2016: Coprocessors – Uses, Abuses and Solutions
HBaseConEast2016: Coprocessors – Uses, Abuses and Solutions
 
Pharma Gastro Intestinal Research, Outsourcing your R&D
Pharma Gastro Intestinal Research, Outsourcing your R&DPharma Gastro Intestinal Research, Outsourcing your R&D
Pharma Gastro Intestinal Research, Outsourcing your R&D
 
Play Learn in Everyday Spaces - Beaconing
Play Learn in Everyday Spaces - BeaconingPlay Learn in Everyday Spaces - Beaconing
Play Learn in Everyday Spaces - Beaconing
 
Apache Phoenix Query Server
Apache Phoenix Query ServerApache Phoenix Query Server
Apache Phoenix Query Server
 
Nuoret somessa - nopeat ja hitaat muutokset
Nuoret somessa - nopeat ja hitaat muutoksetNuoret somessa - nopeat ja hitaat muutokset
Nuoret somessa - nopeat ja hitaat muutokset
 
Productionizing Spark and the REST Job Server- Evan Chan
Productionizing Spark and the REST Job Server- Evan ChanProductionizing Spark and the REST Job Server- Evan Chan
Productionizing Spark and the REST Job Server- Evan Chan
 
e-learning trends 2017
e-learning trends 2017e-learning trends 2017
e-learning trends 2017
 
Actividad tema 2
Actividad tema 2Actividad tema 2
Actividad tema 2
 
Barmenia Kompakt
Barmenia KompaktBarmenia Kompakt
Barmenia Kompakt
 
Formation professionnelle en suisse
Formation professionnelle en suisseFormation professionnelle en suisse
Formation professionnelle en suisse
 
Oppimisen varmistaminen digiohjauksen ja palautteen avulla
Oppimisen varmistaminen digiohjauksen ja palautteen avullaOppimisen varmistaminen digiohjauksen ja palautteen avulla
Oppimisen varmistaminen digiohjauksen ja palautteen avulla
 

Ähnlich wie The Magic Of Tie

Scripting3
Scripting3Scripting3
Scripting3
Nao Dara
 
SPL: The Missing Link in Development
SPL: The Missing Link in DevelopmentSPL: The Missing Link in Development
SPL: The Missing Link in Development
jsmith92
 
Topological indices (t is) of the graphs to seek qsar models of proteins com...
Topological indices (t is) of the graphs  to seek qsar models of proteins com...Topological indices (t is) of the graphs  to seek qsar models of proteins com...
Topological indices (t is) of the graphs to seek qsar models of proteins com...
Jitendra Kumar Gupta
 

Ähnlich wie The Magic Of Tie (20)

Scripting3
Scripting3Scripting3
Scripting3
 
Adventures in Optimization
Adventures in OptimizationAdventures in Optimization
Adventures in Optimization
 
OOP in PHP.pptx
OOP in PHP.pptxOOP in PHP.pptx
OOP in PHP.pptx
 
The History of PHPersistence
The History of PHPersistenceThe History of PHPersistence
The History of PHPersistence
 
Oops in php
Oops in phpOops in php
Oops in php
 
PHP Functions & Arrays
PHP Functions & ArraysPHP Functions & Arrays
PHP Functions & Arrays
 
PHP 5.4
PHP 5.4PHP 5.4
PHP 5.4
 
wget.pl
wget.plwget.pl
wget.pl
 
Your code sucks, let's fix it - DPC UnCon
Your code sucks, let's fix it - DPC UnConYour code sucks, let's fix it - DPC UnCon
Your code sucks, let's fix it - DPC UnCon
 
You code sucks, let's fix it
You code sucks, let's fix itYou code sucks, let's fix it
You code sucks, let's fix it
 
Perl Scripting
Perl ScriptingPerl Scripting
Perl Scripting
 
SPL: The Missing Link in Development
SPL: The Missing Link in DevelopmentSPL: The Missing Link in Development
SPL: The Missing Link in Development
 
Path::Tiny
Path::TinyPath::Tiny
Path::Tiny
 
Subroutines
SubroutinesSubroutines
Subroutines
 
The Origin of Lithium
The Origin of LithiumThe Origin of Lithium
The Origin of Lithium
 
Descobrindo a linguagem Perl
Descobrindo a linguagem PerlDescobrindo a linguagem Perl
Descobrindo a linguagem Perl
 
Topological indices (t is) of the graphs to seek qsar models of proteins com...
Topological indices (t is) of the graphs  to seek qsar models of proteins com...Topological indices (t is) of the graphs  to seek qsar models of proteins com...
Topological indices (t is) of the graphs to seek qsar models of proteins com...
 
Intermediate PHP
Intermediate PHPIntermediate PHP
Intermediate PHP
 
Intro to The PHP SPL
Intro to The PHP SPLIntro to The PHP SPL
Intro to The PHP SPL
 
Web 8 | Introduction to PHP
Web 8 | Introduction to PHPWeb 8 | Introduction to PHP
Web 8 | Introduction to PHP
 

Mehr von brian d foy

The Whitespace in the Perl Community
The Whitespace in the Perl CommunityThe Whitespace in the Perl Community
The Whitespace in the Perl Community
brian d foy
 

Mehr von brian d foy (20)

Conferences for Beginners presentation
Conferences for Beginners presentationConferences for Beginners presentation
Conferences for Beginners presentation
 
20 years in Perl
20 years in Perl20 years in Perl
20 years in Perl
 
PrettyDump Perl 6 (London.pm)
PrettyDump Perl 6 (London.pm)PrettyDump Perl 6 (London.pm)
PrettyDump Perl 6 (London.pm)
 
Dumping Perl 6 (French Perl Workshop)
Dumping Perl 6 (French Perl Workshop)Dumping Perl 6 (French Perl Workshop)
Dumping Perl 6 (French Perl Workshop)
 
Perl v5.26 Features (AmsterdamX.pm)
Perl v5.26 Features (AmsterdamX.pm)Perl v5.26 Features (AmsterdamX.pm)
Perl v5.26 Features (AmsterdamX.pm)
 
Dumping Perl 6 (AmsterdamX.pm)
Dumping Perl 6 (AmsterdamX.pm)Dumping Perl 6 (AmsterdamX.pm)
Dumping Perl 6 (AmsterdamX.pm)
 
6 more things about Perl 6
6 more things about Perl 66 more things about Perl 6
6 more things about Perl 6
 
Perl 5.28 new features
Perl 5.28 new featuresPerl 5.28 new features
Perl 5.28 new features
 
The Surprisingly Tense History of the Schwartzian Transform
The Surprisingly Tense History of the Schwartzian TransformThe Surprisingly Tense History of the Schwartzian Transform
The Surprisingly Tense History of the Schwartzian Transform
 
Perl Power Tools - Saint Perl 6
Perl Power Tools - Saint Perl 6Perl Power Tools - Saint Perl 6
Perl Power Tools - Saint Perl 6
 
The Whitespace in the Perl Community
The Whitespace in the Perl CommunityThe Whitespace in the Perl Community
The Whitespace in the Perl Community
 
CPAN Workshop, Chicago 2014
CPAN Workshop, Chicago 2014CPAN Workshop, Chicago 2014
CPAN Workshop, Chicago 2014
 
Reverse Installing CPAN
Reverse Installing CPANReverse Installing CPAN
Reverse Installing CPAN
 
I ❤ CPAN
I ❤ CPANI ❤ CPAN
I ❤ CPAN
 
Tour of the Perl docs
Tour of the Perl docsTour of the Perl docs
Tour of the Perl docs
 
Create and upload your first Perl module to CPAN
Create and upload your first Perl module to CPANCreate and upload your first Perl module to CPAN
Create and upload your first Perl module to CPAN
 
Perl Conferences for Beginners
Perl Conferences for BeginnersPerl Conferences for Beginners
Perl Conferences for Beginners
 
Backward to DPAN
Backward to DPANBackward to DPAN
Backward to DPAN
 
Perl docs {sux|rulez}
Perl docs {sux|rulez}Perl docs {sux|rulez}
Perl docs {sux|rulez}
 
What's wrong with the perldocs
What's wrong with the perldocsWhat's wrong with the perldocs
What's wrong with the perldocs
 

Kürzlich hochgeladen

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 

Kürzlich hochgeladen (20)

Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 

The Magic Of Tie

  • 1. The Magic of tie brian d foy brian@stonehenge.com Stonehenge Consulting Ser vices May 26, 2006 Dallas-Ft. Worth Perl Mongers
  • 2. Fun with variables Tied variables are really hidden objects The objects have a hidden interface to make them act like normal variables Behind that interface, we do we what
  • 3. Normal variables $value = 5; $other_value = $value; @array = qw( a b c ); $array[3] = ‘d’; $last = $#array shift @array; %hash = map { $_, 1 } @array; $hash{a} = 2; delete $hash{b}; my @keys = keys %hash;
  • 4. Do what we want The tie interface let’s us decide what to do in each case We can store values any way we like tie my $scalar, ‘Tie::Foo’, @args; tie my @array, ‘Tie::Bar’, @args; tie my %hash, ‘Tie::Quux’, @args; tie my $fh, ‘Tie::Baz’, @args;
  • 5. Do what the user knows Scalars, arrays, hashes Common, “Learning Perl” level syntax Hide all of the complexity
  • 6. DBM::Deep Persistent hashes use DBM::Deep; my $db = DBM::Deep->new( quot;foo.dbquot; ); $db->{key} = 'value'; print $db->{key}; # true multi-level support $db->{my_complex} = [ 'hello', { perl => 'rules' }, 42, 99 ];
  • 7. Tie:: modules Tie::Scalar Tie::Array Tie::Hash Tie::Handle Tie::File Tie::Cycle Tie::Toggle Tie::FlipFlop Tie::Handle::CSV Tie::SortHash IO::Scalar IO::String
  • 8. Two variables The normal looking variable and it’s secret life as an object my $object = tie my $scalar, ‘Tie::ClassName’, @args;
  • 9. We do this... Perl does this... $scalar $object->FETCH $scalar = 5 $object->STORE(5)
  • 10. Scalars my $object = tie my $scalar, Tie::Foo- ‘Tie::Foo’, @args; >TIESCALAR( @args ) $n = $scalar; $n = $object->FETCH; $scalar = 5; $object->STORE(5); tied($scalar)->foo(5); $object->foo(5); and a few others: DESTROY, UNTIE
  • 11. Tie::Cycle use Tie::Cycle; tie my $cycle, 'Tie::Cycle', [ qw( FFFFFF 000000 FFFF00 ) ]; print $cycle; # FFFFFF print $cycle; # 000000 print $cycle; # FFFF00 print $cycle; # FFFFFF back to the beginning (tied $cycle)->reset; # back to the beginning
  • 12. IO::Scalar use 5.005; use IO::Scalar; $data = quot;My message:nquot;; ### Open a handle on a string $SH = IO::Scalar->new( $data ); $SH->print(quot;Helloquot;); $SH->print(quot;, world!nBye now!nquot;); print quot;The string is now: quot;, $data, quot;nquot;; == OR == open my $fh, “>”, $variable;
  • 13. Tie::Scalar Base class for tied scalars Override for the parts you need
  • 14. Arrays my $object = tie my @array, Tie::Foo- ‘Tie::Foo’, @args; >TIEARRAY( @args ) $n = $array[$i]; $n = $object->FETCH($i); $array[$i] = 5; $object->STORE($i, 5); $n = @array $object->FETCHSIZE; $#array = $n; $object->STORESIZE($n+1); $#array += $n; $object->EXTEND($n); @array = (); $object->CLEAR; and a few others: DELETE, EXISTS, PUSH, POP, SHIFT, UNSHIFT, SPLICE, DESTROY, UNTIE
  • 15. Tie::Array Base class for tied arrays Override the parts you need
  • 16. Hashes my $obj = tie my %hash, Tie::Foo- ‘Tie::Foo’, @args; >TIEHASH( @args ) $n = $hash{ $key }; $n = $obj->FETCH($key); $hash{ $key } = 5; $obj->STORE($key, 5); delete $hash{ $key }; $obj->DELETE( $key ) exists $hash{ $key }; $obj->EXISTS( $key ) %hash = (); $obj->CLEAR @keys = ( my @keys = keys %hash; $obj->FIRSTKEY, $obj->NEXTKEY ... ) and a few others: SCALAR, UNTIE, DESTROY
  • 17. Tie::Hash Base class for tied hashes Override the parts you need
  • 18. Filehandles my $object = tie my $fh, Tie::Foo- ‘Tie::Foo’, @args; >TIEHANDLE( @args ) print $fh @stuff; $object->PRINT(@stuff); my $line = <$fh> $object->READLINE; close $fh; $object->CLOSE; and a few others: WRITE, PRINTF, READ, DESTROY, UNTIE
  • 19. Tie::Handle Base class for tied handles Override the parts you need