$bool = $obj->mk_aliases( # create an alias to an existing alias_name => 'method'); # method name

Similar documents
use Log::Message private => 0, config => '/our/cf_file'; my $log = Log::Message->new( private => 1, level => 'log', config => '/my/cf_file', );

use Params::Check qw[check allow last_error];

my $reply = $term->get_reply( prompt => 'What is your favourite colour?', choices => [qw blue red green ], default => blue, );

Subroutines. Subroutines. The Basics. aka: user-defined functions, methods, procdures, sub-procedures, etc etc etc.

use attributes (); # optional, to get subroutine declarations = attributes::get(\&foo);

my $full_path = can_run('wget') or warn 'wget is not installed!';

Now applying :unique to lexical variables and to subroutines will result in a compilation error.

NAME SYNOPSIS. Perl version documentation - Pod::Parser. Pod::Parser - base class for creating POD filters and translators.

Hash::Util::FieldHash offers a number of functions in support of The Inside-out Technique of class construction.

Module::Pluggable - automatically give your module the ability to have plugins

# Blocking dequeue with 5-second timeout if (defined(my $item = $q->dequeue_timed(5))) { # Work on $item }

1 Apache2::Filter - Perl API for Apache 2.0 Filtering

NAME SYNOPSIS. Perl version documentation - Pod::Parser. Pod::Parser - base class for creating POD filters and translators.

### build a File::Fetch object ### my $ff = File::Fetch->new(uri => '

my $full_path = can_run('wget') or warn 'wget is not installed!';

package YourModule; require = = qw(munge frobnicate); # symbols to export on request

@EXPORT_OK = qw(munge frobnicate); # symbols to export on request

Data::Dumper - stringified perl data structures, suitable for both printing and eval

Data::Dumper - stringified perl data structures, suitable for both printing and eval

# use a BEGIN block so we print our plan before MyModule is loaded BEGIN { plan tests => 14, todo => [3,4] }

Chapter 1 Getting Started

CS 105 Perl: Perl subroutines and Disciplined Perl

CS 105 Perl: Completing the Toolbox

pairs unpairs pairkeys pairvalues pairfirst pairgrep pairmap

This document describes version 2.07 of File::Path, released

Learning Perl Objects, References, and Modules

package CLASS_NAME; use Class::Struct; # declare struct, based on array, implicit class name: struct( ELEMENT_NAME => ELEMENT_TYPE,...

Be sure to read ENCODING if your Pod contains non-ascii characters.

The Eobj Perl environment

Exploring Perl 6 Through Its Modules. Jonathan 6guts.wordpress.com

threads::shared - Perl extension for sharing data structures between threads

$parser->parse_from_file ('file.pod', 'file.tex');

1 Apache2::RequestUtil - Perl API for Apache

This document describes version 2.09 of File::Path, released

This document describes version 2.10 of Switch, released Dec 29, 2003.

This document describes version 0.87 of Attribute::Handlers, released September 21, 2009.

[Skip ahead to DESCRIPTION if you don't care about the whys and wherefores of this control structure]

CMSC 132: Object-Oriented Programming II

CS 105 Perl: Modules and Objects

Perl (5 Days Content)

1 APR::URI - Perl API for URI manipulations

PERL Scripting - Course Contents

$pat = '(?{ $foo = 1 })'; use re 'eval'; /foo${pat}bar/; # won't fail (when not under -T # switch)

Your first C++ program

1 Decorators. 2 Descriptors. 3 Static Variables. 4 Anonymous Classes. Sandeep Sadanandan (TU, Munich) Python For Fine Programmers July 13, / 19

Distributed Real-Time Control Systems. Lecture 14 Intro to C++ Part III

Tieing and Overloading Objects in Perl. Dave Cross Magnum Solutions

Perl version documentation - overload NAME SYNOPSIS DESCRIPTION Declaration of overloaded functions Calling Conventions for Binary Operations

Intermediate Perl Table of Contents Intermediate Perl Foreword Preface Structure of This Book Conventions Used in This Book Using Code Examples

C++ Functions. Procedural-based Programming. what s a functions

COMP 110/L Lecture 19. Kyle Dewey

sinon Documentation Release Kir Chou

pm_to_blib({ 'lib/foo/bar.pm' => 'blib/lib/foo/bar.pm' }); Handles the installing and uninstalling of perl modules, scripts, man pages, etc...

Implementing Functions at the Machine Level

Inheritance. Benefits of Java s Inheritance. 1. Reusability of code 2. Code Sharing 3. Consistency in using an interface. Classes

Cross-platform daemonization tools.

Definition of DJ (Diminished Java)

use File::Find; find({ wanted => \&process, follow => 1 }, '.');

By default, optional warnings are disabled, so any legacy code that doesn't attempt to control the warnings will work unchanged.

Magit-Popup User Manual

School of Informatics, University of Edinburgh

Arguments of the use overload directive are (key, value) pairs. For the full set of legal keys, see Overloadable Operations below.

perl -MO=Deparse[,-d][,-fFILE][,-p][,-q][,-l] [,-sletters][,-xlevel] prog.pl

perl -MO=Deparse[,-d][,-fFILE][,-p][,-q][,-l] [,-sletters][,-xlevel] prog.pl

This class is a formatter that takes Pod and renders it as XHTML validating HTML.

Compilers. Cool Semantics II. Alex Aiken

CS 3101 _ programming languages (perl)

Inheritance in Ruby. You are familiar with the idea of inheritance and how to use this in programming.

NEXT - Provide a pseudo-class NEXT (et al) that allows method redispatch

Chapter 8 ( ) Control Abstraction. Subprograms Issues related to subprograms How is control transferred to & from the subprogram?

This module provide a convenient way to create directories of arbitrary depth and to delete an entire directory subtree from the filesystem.

Go Cheat Sheet. Operators. Go in a Nutshell. Declarations. Basic Syntax. Hello World. Functions. Comparison. Arithmetic. Credits

# Rather than print STDERR "# here s what went wrong\n" diag("here s what went wrong");

### build an Archive::Extract object ### my $ae = Archive::Extract->new( archive => 'foo.tgz' );

Pod::Simple::HTMLBatch - convert several Pod files to several HTML files. perl -MPod::Simple::HTMLBatch -e 'Pod::Simple::HTMLBatch::go' in out

Control Abstraction. Hwansoo Han

Pod::Usage, pod2usage() - print a usage message from embedded pod documentation

1 Apache2::ServerUtil - Perl API for Apache server

lock_ref_keys unlock_ref_keys lock_ref_value unlock_ref_value lock_hashref unlock_hashref lock_ref_keys_plus hidden_ref_keys legal_ref_keys

1 ModPerl::RegistryCooker - Cook mod_perl 2.0

Object Oriented Programming with Perl

runs all the testscripts named as arguments and checks standard output for the expected strings in TAP format.

Generating Continuation Passing Style Code for the Co-op Language

# Rather than print STDERR "# here's what went wrong\n" diag("here's what went wrong");

Perl Virtual Database Module

A Small Interpreted Language

Programming Languages: Application and Interpretation

GNU ccscript Scripting Guide IV

lock_ref_keys unlock_ref_keys lock_ref_value unlock_ref_value lock_hashref unlock_hashref lock_ref_keys_plus hidden_ref_keys legal_ref_keys

Class, Variable, Constructor, Object, Method Questions

COMS 3101 Programming Languages: Perl. Lecture 6

As of Perl there is a new interface for plugging and using other regular expression engines than the default one.

Super-Classes and sub-classes

The Essence of Object Oriented Programming with Java and UML. Chapter 2. The Essence of Objects. What Is an Object-Oriented System?

This document was created in February, 2011, and the last major revision was in February, 2013.

Fortunately, the layout is much more legible, more like BASIC's PRINT USING statement. Think of it as a poor man's nroff(1). nroff

Introduction to Perl Session 6. special variables subroutines Introduction to Perl

Principles of Object Oriented Programming. Lecture 4

Late Binding; OOP as a Racket Pattern

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

Transcription:

NAME SYNOPSIS Object::Accessor - interface to create per object accessors ### using the object $obj = Object::Accessor->new; # create object $obj = Object::Accessor->new(@list); # create object with accessors $obj = Object::Accessor->new(\%h); # create object with accessors # and their allow handlers $bool = $obj->mk_accessors('foo'); # create accessors $bool = $obj->mk_accessors( # create accessors with input {foo => ALLOW_HANDLER ); # validation $bool = $obj->mk_aliases( # create an alias to an existing alias_name => 'method'); # method name $clone = $obj->mk_clone; # create a clone of original # object without data $bool = $obj->mk_flush; # clean out all data @list = $obj->ls_accessors; # retrieves a list of all # accessors for this object $bar = $obj->foo('bar'); # set 'foo' to 'bar' $bar = $obj->foo(); # retrieve 'bar' again $sub = $obj->can('foo'); # retrieve coderef for # 'foo' accessor $bar = $sub->('bar'); # set 'foo' via coderef $bar = $sub->(); # retrieve 'bar' by coderef ### using the object as base class package My::Class; use base 'Object::Accessor'; $obj = My::Class->new; # create base object $bool = $obj->mk_accessors('foo'); # create accessors, etc... ### make all attempted access to non-existent accessors fatal ### (defaults to false) $Object::Accessor::FATAL = 1; ### enable debugging $Object::Accessor::DEBUG = 1; ### advanced usage -- callbacks { my $obj = Object::Accessor->new('foo'); $obj->register_callback( sub {... ); $obj->foo( 1 ); # these calls invoke the callback you registered $obj->foo() # which allows you to change the get/set Page 1

# behaviour and what is returned to the caller. ### advanced usage -- lvalue attributes { my $obj = Object::Accessor::Lvalue->new('foo'); print $obj->foo = 1; # will print 1 ### advanced usage -- scoped attribute values { my $obj = Object::Accessor->new('foo'); $obj->foo( 1 ); ### bind the scope of the value of attribute 'foo' ### to the scope of '$x' -- when $x goes out of ### scope, 'foo's previous value will be restored { $obj->foo( 2 => \my $x ); print $obj->foo, ' ', $x; # will print '2 2' DESCRIPTION Object::Accessor provides an interface to create per object accessors (as opposed to per Class accessors, as, for example, Class::Accessor provides). You can choose to either subclass this module, and thus using its accessors on your own module, or to store an Object::Accessor object inside your own object, and access the accessors from there. See the SYNOPSIS for examples. METHODS $object = Object::Accessor->new( [ARGS] ); Creates a new (and empty) Object::Accessor object. This method is inheritable. Any arguments given to new are passed straight to mk_accessors. If you want to be able to assign to your accessors as if they were lvalues, you should create your object in the Object::Accessor::Lvalue namespace instead. See the section on LVALUE ACCESSORS below. $bool = $object->mk_accessors( @ACCESSORS \%ACCESSOR_MAP ); Creates a list of accessors for this object (and NOT for other ones in the same class!). Will not clobber existing data, so if an accessor already exists, requesting to create again is effectively a no-op. When providing a hashref as argument, rather than a normal list, you can specify a list of key/value pairs of accessors and their respective input validators. The validators can be anything that Params::Check's allow function accepts. Please see its manpage for details. For example: $object->mk_accessors( { foo => qr/^\d+$/, # digits only bar => [0,1], # booleans zot => \&my_sub # a custom verification sub ); Page 2

Returns true on success, false on failure. Accessors that are called on an object, that do not exist return undef by default, but you can make this a fatal error by setting the global variable $FATAL to true. See the section on GLOBAL VARIABLES for details. Note that you can bind the values of attributes to a scope. This allows you to temporarily change a value of an attribute, and have it's original value restored up on the end of it's bound variable's scope; For example, in this snippet of code, the attribute foo will temporarily be set to 2, until the end of the scope of $x, at which point the original value of 1 will be restored. my $obj = Object::Accessor->new; $obj->mk_accessors('foo'); $obj->foo( 1 ); ### bind the scope of the value of attribute 'foo' ### to the scope of '$x' -- when $x goes out of ### scope, 'foo' previous value will be restored { $obj->foo( 2 => \my $x ); print $obj->foo, ' ', $x; # will print '2 2' Note that all accessors are read/write for everyone. See the TODO section for details. @list = $self->ls_accessors; Returns a list of accessors that are supported by the current object. The corresponding coderefs can be retrieved by passing this list one by one to the can method. $ref = $self->ls_allow(key) Returns the allow handler for the given key, which can be used with Params::Check's allow() handler. If there was no allow handler specified, an allow handler that always returns true will be returned. $bool = $self->mk_aliases( alias => method, [alias2 => method2,...] ); Creates an alias for a given method name. For all intents and purposes, these two accessors are now identical for this object. This is akin to doing the following on the symbol table level: *alias = *method This allows you to do the following: $self->mk_accessors('foo'); $self->mk_aliases( bar => 'foo' ); $self->bar( 42 ); print $self->foo; # will print 42 $clone = $self->mk_clone; Makes a clone of the current object, which will have the exact same accessors as the current object, but without the data stored in them. Page 3

$bool = $self->mk_flush; Flushes all the data from the current object; all accessors will be set back to their default state of undef. Returns true on success and false on failure. $bool = $self->mk_verify; Checks if all values in the current object are in accordance with their own allow handler. Specifically useful to check if an empty initialised object has been filled with values satisfying their own allow criteria. $bool = $self->register_callback( sub {... ); This method allows you to register a callback, that is invoked every time an accessor is called. This allows you to munge input data, access external data stores, etc. You are free to return whatever you wish. On a set call, the data is even stored in the object. Below is an example of the use of a callback. $object->some_method( "some_value" ); my $callback = sub { my $self = shift; # the object my $meth = shift; # "some_method" my $val = shift; # ["some_value"] # could be undef -- check 'exists'; # if scalar @$val is empty, it was a 'get' # your code here return $new_val; # the value you want to be set/returned To access the values stored in the object, circumventing the callback structure, you should use the get and set methods documented further down. $bool = $self->can( METHOD_NAME ) This method overrides UNIVERAL::can in order to provide coderefs to accessors which are loaded on demand. It will behave just like UNIVERSAL::can where it can -- returning a class method if it exists, or a closure pointing to a valid accessor of this particular object. You can use it as follows: $sub = $object->can('some_accessor'); $sub->('foo'); $foo = $sub->(); # retrieve the coderef # 'some_accessor' now set # to 'foo' for $object # retrieve the contents # of 'some_accessor' See the SYNOPSIS for more examples. $val = $self-> get( METHOD_NAME ); Method to directly access the value of the given accessor in the object. It circumvents all calls to allow checks, callbacks, etc. Use only if you Know What You Are Doing! General usage for this functionality would be in your Page 4

own custom callbacks. $bool = $self-> set( METHOD_NAME => VALUE ); Method to directly set the value of the given accessor in the object. It circumvents all calls to allow checks, callbacks, etc. Use only if you Know What You Are Doing! General usage for this functionality would be in your own custom callbacks. $bool = $self-> alias( ALIAS => METHOD ); Method to directly alias one accessor to another for this object. It circumvents all sanity checks, etc. Use only if you Know What You Are Doing! LVALUE ACCESSORS Object::Accessor supports lvalue attributes as well. To enable these, you should create your objects in the designated namespace, Object::Accessor::Lvalue. For example: my $obj = Object::Accessor::Lvalue->new('foo'); $obj->foo += 1; print $obj->foo; will actually print 1 and work as expected. Since this is an optional feature, that's not desirable in all cases, we require you to explicitly use the Object::Accessor::Lvalue class. Doing the same on the standard Object>Accessor> class would generate the following code & errors: my $obj = Object::Accessor->new('foo'); $obj->foo += 1; Can't modify non-lvalue subroutine call CAVEATS Note that lvalue support on AUTOLOAD routines is a perl 5.8.x feature. See perldoc perl58delta for details. * Allow handlers * Callbacks GLOBAL VARIABLES $Object::Accessor::FATAL Due to the nature of lvalue subs, we never get access to the value you are assigning, so we can not check it against your allow handler. Allow handlers are therefor unsupported under lvalue conditions. See perldoc perlsub for details. Due to the nature of lvalue subs, we never get access to the value you are assigning, so we can not check provide this value to your callback. Furthermore, we can not distinguish between a get and a set call. Callbacks are therefor unsupported under lvalue conditions. See perldoc perlsub for details. Set this variable to true to make all attempted access to non-existent accessors be fatal. This defaults to false. Page 5

$Object::Accessor::DEBUG Set this variable to enable debugging output. This defaults to false. TODO Create read-only accessors CAVEATS BUG REPORTS AUTHOR COPYRIGHT Currently all accessors are read/write for everyone. Perhaps a future release should make it possible to have read-only accessors as well. If you use codereferences for your allow handlers, you will not be able to freeze the data structures using Storable. Due to a bug in storable (until at least version 2.15), qr// compiled regexes also don't de-serialize properly. Although this bug has been reported, you should be aware of this issue when serializing your objects. You can track the bug here: http://rt.cpan.org/ticket/display.html?id=1827 Please report bugs or other issues to <bug-object-accessor@rt.cpan.org>. This module by Jos Boumans <kane@cpan.org>. This library is free software; you may redistribute and/or modify it under the same terms as Perl itself. Page 6