diff options
Diffstat (limited to 'lib/Class/MakeMethods/Utility')
| -rw-r--r-- | lib/Class/MakeMethods/Utility/ArraySplicer.pm | 243 | ||||
| -rw-r--r-- | lib/Class/MakeMethods/Utility/DiskCache.pm | 165 | ||||
| -rw-r--r-- | lib/Class/MakeMethods/Utility/Inheritable.pm | 126 | ||||
| -rw-r--r-- | lib/Class/MakeMethods/Utility/Ref.pm | 171 | ||||
| -rw-r--r-- | lib/Class/MakeMethods/Utility/TextBuilder.pm | 207 |
5 files changed, 912 insertions, 0 deletions
diff --git a/lib/Class/MakeMethods/Utility/ArraySplicer.pm b/lib/Class/MakeMethods/Utility/ArraySplicer.pm new file mode 100644 index 0000000..e07a796 --- /dev/null +++ b/lib/Class/MakeMethods/Utility/ArraySplicer.pm @@ -0,0 +1,243 @@ +=head1 NAME + +Class::MakeMethods::Utility::ArraySplicer - Common array ops + +=head1 SYNOPSIS + + use Class::MakeMethods::Utility::ArraySplicer; + + # Get one or more values + $value = array_splicer( $array_ref, $index ); + @values = array_splicer( $array_ref, $index_array_ref ); + + # Set one or more values + array_splicer( $array_ref, $index => $new_value, ... ); + + # Splice selected values in or out + array_splicer( $array_ref, [ $start_index, $end_index], [ @values ]); + +=head1 DESCRIPTION + +This module provides a utility function and several associated constants which support a general purpose array-splicer interface, used by several of the Standard and Composite method generators. + +=cut + +######################################################################## + +package Class::MakeMethods::Utility::ArraySplicer; + +$VERSION = 1.000; + +@EXPORT_OK = qw( + array_splicer + array_set array_clear array_push array_pop array_unshift array_shift +); +sub import { require Exporter and goto &Exporter::import } # lazy Exporter + +use strict; + +######################################################################## + +=head2 array_splicer + +This is a general-purpose array accessor function. Depending on the arguments passed to it, it will get, set, slice, splice, or otherwise modify your array. + +=over 4 + +=item * + +If called without any arguments, returns the contents of the array in list context, or an array reference in scalar context (or undef). + + # Get all values + $value_ref = array_splicer( $array_ref ); + @values = array_splicer( $array_ref ); + +=item * + +If called with a single numeric argument, uses that argument as an index to retrieve from the referenced array, and returns that value (or undef). + + # Get one value + $value = array_splicer( $array_ref, $index ); + +=item * + +If called with a single array ref argument, sets the contents of the array to match the contents of the provided one. + + # Set contents of array + array_splicer( $array_ref, [ $value1, $value2, ... ] ); + + # Reset the array contents to empty + array_splicer( $array_ref, [] ); + +=item * + +If called with a two arguments, the first undefined and the second an array ref argument, uses that array's contents as a list of indexes to return a slice of the referenced array. + + # Get slice of values + @values = array_splicer( $array_ref, undef, [ $index1, $index2, ... ] ); + +=item * + +If called with a list of argument pairs, each with a numeric index and an associated value, stores the value at the given index in the referenced array. The current value in each position will be overwritten, and later arguments with the same index will override earlier ones. Returns the current array-ref value. + + # Set one or more values by index + array_splicer( $array_ref, $index1 => $value1, $index2 => $value2, ... ); + +=item * + +If called with a list of argument pairs, each with the first item being a reference to an array of up to two numbers, loops over each pair and uses those numbers to splice the value array. + + # Splice selected values in or out + array_splicer( $array_ref, [ $start_index, $count], [ @values ]); + +The first controlling number is the position at which the splice will begin. Zero will start before the first item in the list. Negative numbers count backwards from the end of the array. + +The second number is the number of items to be removed from the list. If it is omitted, or undefined, or zero, no items are removed. If it is a positive integer, that many items will be returned. + +If both numbers are omitted, or are both undefined, they default to containing the entire value array. + +If the second argument is undef, no values will be inserted; if it is a non-reference value, that one value will be inserted; if it is an array-ref, its values will be copied. + +The method returns the items that removed from the array, if any. + +Here are some examples of common splicing operations. + + # Insert an item at position in the array + $obj->bar([3], 'Potatoes' ); + + # Remove 1 item from position 3 in the array + $obj->bar([3, 1], undef ); + + # Set a new value at position 2, and return the old value + print $obj->bar([2, 1], 'Froth' ); + + # Unshift an item onto the front of the list + array_splicer( $array_ref, [0], 'Bubbles' ); + + # Shift the first item off of the front of the list + print array_splicer( $array_ref, [0, 1], undef ); + + # Push an item onto the end of the list + array_splicer( $array_ref, [undef], 'Bubbles' ); + + # Pop the last item off of the end of the list + print array_splicer( $array_ref, [undef, 1], undef ); + +=back + +=cut + +sub array_splicer { + my $value_ref = shift; + + # RETRIEVE VALUES + if ( scalar(@_) == 0 ) { + return wantarray ? @$value_ref : $value_ref; + + # FETCH BY INDEX + } elsif ( scalar(@_) == 1 and length($_[0]) and ! ref($_[0]) and $_[0] !~ /\D/) { + $value_ref->[ $_[0] ] + + # SET CONTENTS + } elsif ( scalar(@_) == 1 and ref $_[0] eq 'ARRAY' ) { + @$value_ref = @{ $_[0] }; + return wantarray ? @$value_ref : $value_ref; + + # ASSIGN BY INDEX + } elsif ( ! ( scalar(@_) % 2 ) and ! grep { ! ( length($_) and ! ref($_) and $_ !~ /\D/ ) } map { $_[$_] } grep { ! ( $_ % 2 ) } ( 0 .. $#_ ) ) { + while ( scalar(@_) ) { + my $key = shift(); + $value_ref->[ $key ] = shift(); + } + $value_ref; + + # SLICE + } elsif ( ! scalar(@_) == 2 and ! defined $_[0] and ref $_[1] eq 'ARRAY' ) { + @{$value_ref}[ @{ $_[1] } ] + + # SPLICE + } elsif ( ! scalar(@_) % 2 and ref $_[0] eq 'ARRAY' ) { + my @results; + while ( scalar(@_) ) { + my $key = shift(); + my $value = shift(); + my @values = ! ( $value ) ? () : ! ref ( $value ) ? $value : @$value; + my $key_v = $key->[0]; + my $key_c = $key->[1]; + if ( defined $key_v ) { + if ( $key_c ) { + # straightforward two-value splice + } else { + # insert at position + $key_c = 0; + } + } else { + if ( ! defined $key_c ) { + # target the entire list + $key_v = 0; + $key_c = scalar @$value_ref; + } elsif ( $key_c ) { + # take count items off the end + $key_v = - $key_c + } else { + # insert at the end + $key_v = scalar @$value_ref; + $key_c = 0; + } + } + push @results, splice @$value_ref, $key_v, $key_c, @values + } + ( ! wantarray and scalar @results == 1 ) ? $results[0] : @results; + + } else { + Carp::confess 'Unexpected arguments to array accessor: ' . join(', ', map "'$_'", @_ ); + } +} + +######################################################################## + +=head2 Constants + +There are also constants symbols to facilitate some common combinations of splicing arguments: + + # Reset the array contents to empty + array_splicer( $array_ref, array_clear ); + + # Set the array contents to provided values + array_splicer( $array_ref, array_splice, [ 2, 3 ] ); + + # Unshift an item onto the front of the list + array_splicer( $array_ref, array_unshift, 'Bubbles' ); + + # Shift it back off again + print array_splicer( $array_ref, array_shift ); + + # Push an item onto the end of the list + array_splicer( $array_ref, array_push, 'Bubbles' ); + + # Pop it back off again + print array_splicer( $array_ref, array_pop ); + +=cut + +use constant array_splice => undef; +use constant array_clear => ( [] ); + +use constant array_push => [undef]; +use constant array_pop => ( [undef, 1], undef ); + +use constant array_unshift => [0]; +use constant array_shift => ( [0, 1], undef ); + +######################################################################## + +=head1 SEE ALSO + +See L<Class::MakeMethods> for general information about this distribution. + +See L<Class::MakeMethods::Standard::Hash> and numerous other classes for +examples of usage. + +=cut + +1; diff --git a/lib/Class/MakeMethods/Utility/DiskCache.pm b/lib/Class/MakeMethods/Utility/DiskCache.pm new file mode 100644 index 0000000..653303c --- /dev/null +++ b/lib/Class/MakeMethods/Utility/DiskCache.pm @@ -0,0 +1,165 @@ +package Class::MakeMethods::Utility::DiskCache; + +$VERSION = 1.008; + +@EXPORT_OK = qw( disk_cache ); +sub import { require Exporter and goto &Exporter::import } # lazy Exporter + +use strict; +use Carp; +use File::Spec; +use File::Path; + +######################################################################## + +use vars qw( $DiskCacheDir ); + +my $IndexFile = "methods.ix"; # file also serves as timestamp +my $FileEnding = ".mm"; + +sub import { + my $package = shift; + if ( scalar @_ ) { + $DiskCacheDir = shift; + } +} + +######################################################################## + +my %HaveCheckedFreshness; + +# $result = disk_cache( $package, $file, $sub, @args ); +sub disk_cache { + my ( $full_funct, $args_string, $function, @args ) = @_; + + unless ( $DiskCacheDir and -e $DiskCacheDir ) { + return &$function( @args ); + } + + my ($package, $func_name) = ( $full_funct =~ /^(.+)::(\w+)$/ ); + + my $pack_dir = File::Spec->catdir( $DiskCacheDir, split /::/, $package ); + if ( ! -e $pack_dir and -w $DiskCacheDir ) { + mkpath($pack_dir, 0, 07777); + } + + unless ( defined $HaveCheckedFreshness{$package} ) { + + my $idx = File::Spec->catfile( $pack_dir, $IndexFile ); + + my $signature = dependency_signature($package); + + if ( -e $idx and read_file( $idx ) eq $signature ) { + $HaveCheckedFreshness{$package} = 1; + } else { + if ( ! -w $pack_dir ) { + # The index is out of date, but not writable -- abandon it + $HaveCheckedFreshness{ $package } = 0; + } else { + rmtree($pack_dir, 0, 1); + mkpath($pack_dir, 0, 07777); + + write_file( $idx, $signature ); + $HaveCheckedFreshness{$package} = 1; + } + } + } + + unless ( $HaveCheckedFreshness{$package} ) { + return &$function( @args ); + } + + my $func_dir = File::Spec->catdir( $pack_dir, $func_name ); + + if ( ! -e $func_dir and -w $pack_dir ) { + mkpath($func_dir, 0, 07777); + } + my $file = File::Spec->catfile( $func_dir, $args_string . $FileEnding ); + + if ( -e $file ) { + return read_file( $file ); + } + + my $value = ( &$function( @args ) ); + + if ( -e $func_dir and -w $func_dir ) { + write_file( $file, $value ); + } else { + warn "Can't cache: $file\n"; + } + + return $value; +} + +######################################################################## + +sub dependency_signature { + my @sources = shift; + my @results; + no strict 'refs'; + while ( my $class = shift @sources ) { + push @sources, @{"$class\::ISA"}; + push @results, $class unless ( grep { $_ eq $class } @results ); + } + + foreach ( @results ) { + s!::!/!g; + $_ .= '.pm'; + } + return join "\n", map { $_ . ' '. (stat($::INC{ $_ }))[9] } @results; +} + +######################################################################## + +sub read_file { + my $file = shift; + # warn "Reading file: $file\n"; + local *FILE; + open FILE, "$file" or die "Can't open $file: $!"; + local $/ = undef; + return <FILE>; +} + +sub write_file { + my $file = shift; + # warn "Writing file: $file \n"; + local *FILE; + open FILE, ">$file" or die "Can't write to $file: $!"; + print FILE shift(); +} + +sub read_dir { + my $dir = shift; + local *DIR; + opendir(DIR, $dir); + readdir(DIR); +} + +######################################################################## + +1; + +__END__ + +=head1 NAME + +Class::MakeMethods::Utility::DiskCache - Optional Template feature + +=head1 SYNOPSIS + + use Class::MakeMethods::Utility::DiskCache qw( /my/code/dir ); + +=head1 DESCRIPTION + +To enable disk caching of Class::MakeMethods::Template generated +code, create an empty directory and pass it to the DiskCache package: + + use Class::MakeMethods::Utility::DiskCache qw( /my/code/dir ); + +This has a mixed effect on performance, but has the notable advantage of letting you view the subroutines that are being generated by your templates. + +=head1 SEE ALSO + +See L<Class::MakeMethods::Template> for more information. + +=cut
\ No newline at end of file diff --git a/lib/Class/MakeMethods/Utility/Inheritable.pm b/lib/Class/MakeMethods/Utility/Inheritable.pm new file mode 100644 index 0000000..e1ec9ae --- /dev/null +++ b/lib/Class/MakeMethods/Utility/Inheritable.pm @@ -0,0 +1,126 @@ +=head1 NAME + +Class::MakeMethods::Utility::Inheritable - "Inheritable" data + + +=head1 SYNOPSIS + + package MyClass; + sub new { ... } + + package MySubclass; + @ISA = 'MyClass'; + ... + my $obj = MyClass->new(...); + my $subobj = MySubclass->new(...); + + use Class::MakeMethods::Utility::Inheritable qw(get_vvalue set_vvalue ); + + my $dataset = {}; + set_vvalue($dataset, 'MyClass', 'Foobar'); # Set value for class + get_vvalue($dataset, 'MyClass'); # Gets value "Foobar" + + get_vvalue($dataset, $obj); # Objects "inherit" + set_vvalue($dataset, $obj, 'Foible'); # Until you override + get_vvalue($dataset, $obj); # Now finds "Foible" + + get_vvalue($dataset, 'MySubclass'); # Subclass "inherits" + get_vvalue($dataset, $subobj); # As do its objects + set_vvalue($dataset, 'MySubclass', 'Foozle'); # Until we override it + get_vvalue($dataset, 'MySubclass'); # Now finds "Foozle" + + get_vvalue($dataset, $subobj); # Change cascades down + set_vvalue($dataset, $subobj, 'Foolish'); # Until we override again + + get_vvalue($dataset, 'MyClass'); # Superclass is unchanged + +=head1 DESCRIPTION + +This module provides several functions which allow you to store values in a hash corresponding to both objects and classes, and to retrieve those values by searching a object's inheritance tree until it finds a matching entry. + +This functionality is used by Class::MakeMethods::Standard::Inheritable and Class::MakeMethods::Composite::Inheritable to construct methods that can both store class data and be overriden on a per-object level. + +=cut + +######################################################################## + +package Class::MakeMethods::Utility::Inheritable; + +$VERSION = 1.000; + +@EXPORT_OK = qw( get_vvalue set_vvalue find_vself ); +sub import { require Exporter and goto &Exporter::import } # lazy Exporter + +use strict; + +######################################################################## + +=head1 REFERENCE + +=head2 find_vself + + $vself = find_vself( $dataset, $instance ); + +Searches $instance's inheritance tree until it finds a matching entry in the dataset, and returns either the instance, the class that matched, or undef. + +=cut + +sub find_vself { + my $dataset = shift; + my $instance = shift; + + return $instance if ( exists $dataset->{$instance} ); + + my $v_self; + my @isa_search = ( ref($instance) || $instance ); + while ( scalar @isa_search ) { + $v_self = shift @isa_search; + return $v_self if ( exists $dataset->{$v_self} ); + no strict 'refs'; + unshift @isa_search, @{"$v_self\::ISA"}; + } + return; +} + +=head2 get_vvalue + + $value = get_vvalue( $dataset, $instance ); + +Searches $instance's inheritance tree until it finds a matching entry in the dataset, and returns that value + +=cut + +sub get_vvalue { + my $dataset = shift; + my $instance = shift; + my $v_self = find_vself($dataset, $instance); + # warn "Dataset: " . join( ', ', %$dataset ); + # warn "Retrieving $dataset -> $instance ($v_self): '$dataset->{$v_self}'"; + return $v_self ? $dataset->{$v_self} : (); +} + +=head2 set_vvalue + + $value = set_vvalue( $dataset, $instance, $value ); + +Searches $instance's inheritance tree until it finds a matching entry in the dataset, and returns that value + +=cut + +sub set_vvalue { + my $dataset = shift; + my $instance = shift; + my $value = shift; + if ( defined $value ) { + # warn "Setting $dataset -> $instance = $value"; + $dataset->{$instance} = $value; + } else { + # warn "Clearing $dataset -> $instance"; + delete $dataset->{$instance}; + undef; + } +} + +######################################################################## + +1; diff --git a/lib/Class/MakeMethods/Utility/Ref.pm b/lib/Class/MakeMethods/Utility/Ref.pm new file mode 100644 index 0000000..9c356f4 --- /dev/null +++ b/lib/Class/MakeMethods/Utility/Ref.pm @@ -0,0 +1,171 @@ +=head1 NAME + +Class::MakeMethods::Utility::Ref - Deep copying and comparison + +=head1 SYNOPSIS + + use Class::MakeMethods::Utility::Ref qw( ref_clone ref_compare ); + + $deep_copy = ref_clone( $original ); + $positive_zero_or_negative = ref_compare( $item_a, $item_b ); + +=head1 DESCRIPTION + +This module provides utility functions to copy and compare arbitrary references, including full traversal of nested data structures. + +=cut + +######################################################################## + +package Class::MakeMethods::Utility::Ref; + +$VERSION = 1.000; + +@EXPORT_OK = qw( ref_clone ref_compare ); +sub import { require Exporter and goto &Exporter::import } # lazy Exporter + +use strict; + +###################################################################### + +=head2 REFERENCE + +The following functions are provided: + +=head2 ref_clone() + +Make a recursive copy of a reference. + +=cut + +use vars qw( %CopiedItems ); + +# $deep_copy = ref_clone( $value_or_ref ); +sub ref_clone { + local %CopiedItems = (); + _clone( @_ ); +} + +# $copy = _clone( $value_or_ref ); +sub _clone { + my $source = shift; + + my $ref_type = ref $source; + return $source if (! $ref_type); + + return $CopiedItems{ $source } if ( exists $CopiedItems{ $source } ); + + my $class_name; + if ( "$source" =~ /^\Q$ref_type\E\=([A-Z]+)\(0x[0-9a-f]+\)$/ ) { + $class_name = $ref_type; + $ref_type = $1; + } + + my $copy; + if ($ref_type eq 'SCALAR') { + $copy = \( $$source ); + } elsif ($ref_type eq 'REF') { + $copy = \( _clone ($$source) ); + } elsif ($ref_type eq 'HASH') { + $copy = { map { _clone ($_) } %$source }; + } elsif ($ref_type eq 'ARRAY') { + $copy = [ map { _clone ($_) } @$source ]; + } else { + $copy = $source; + } + + bless $copy, $class_name if $class_name; + + $CopiedItems{ $source } = $copy; + + return $copy; +} + +###################################################################### + +=head2 ref_compare() + +Attempt to recursively compare two references. + +If they are not the same, try to be consistent about returning a +positive or negative number so that it can be used for sorting. +The sort order is kinda arbitrary. + +=cut + +use vars qw( %ComparedItems ); + +# $positive_zero_or_negative = ref_compare( $A, $B ); +sub ref_compare { + local %ComparedItems = (); + _compare( @_ ); +} + +# $positive_zero_or_negative = _compare( $A, $B ); +sub _compare { + my($A, $B, $ignore_class) = @_; + + # If they're both simple scalars, use string comparison + return $A cmp $B unless ( ref($A) or ref($B) ); + + # If either one's not a reference, put that one first + return 1 unless ( ref($A) ); + return - 1 unless ( ref($B) ); + + # Check to see if we've got two references to the same structure + return 0 if ("$A" eq "$B"); + + # If we've already seen these items repeatedly, we may be running in circles + return undef if ($ComparedItems{ $A } ++ > 2 and $ComparedItems{ $B } ++ > 2); + + # Check the ref values, which may be data types or class names + my $ref_A = ref($A); + my $ref_B = ref($B); + return $ref_A cmp $ref_B if ( ! $ignore_class and $ref_A ne $ref_B ); + + # Extract underlying data types + my $type_A = ("$A" =~ /^\Q$ref_A\E\=([A-Z]+)\(0x[0-9a-f]+\)$/) ? $1 : $ref_A; + my $type_B = ("$B" =~ /^\Q$ref_B\E\=([A-Z]+)\(0x[0-9a-f]+\)$/) ? $1 : $ref_B; + return $type_A cmp $type_B if ( $type_A ne $type_B ); + + if ($type_A eq 'HASH') { + my @kA = sort keys %$A; + my @kB = sort keys %$B; + return ( $#kA <=> $#kB ) if ( $#kA != $#kB ); + foreach ( 0 .. $#kA ) { + return ( _compare($kA[$_], $kB[$_]) or + _compare($A->{$kA[$_]}, $B->{$kB[$_]}) or next ); + } + return 0; + } elsif ($type_A eq 'ARRAY') { + return ( $#$A <=> $#$B ) if ( $#$A != $#$B ); + foreach ( 0 .. $#$A ) { + return ( _compare($A->[$_], $B->[$_]) or next ); + } + return 0; + } elsif ($type_A eq 'SCALAR' or $type_A eq 'REF') { + return _compare($$A, $$B); + } else { + return ("$A" cmp "$B") + } +} + +######################################################################## + +=head1 SEE ALSO + +See L<Class::MakeMethods> for general information about this distribution. + +See L<Ref> for the original version of the clone and compare functions used above. + +See L<Clone> (v0.09 on CPAN as of 2000-09-21) for a clone method with an XS implementation. + +The Perl6 RFP #67 proposes including clone functionality in the core. + +See L<Data::Compare> (v0.01 on CPAN as of 1999-04-24) for a Compare method which checks two references for similarity, but it does not provide positive/negative values for ordering purposes. + +=cut + +###################################################################### + +1; diff --git a/lib/Class/MakeMethods/Utility/TextBuilder.pm b/lib/Class/MakeMethods/Utility/TextBuilder.pm new file mode 100644 index 0000000..3bc2767 --- /dev/null +++ b/lib/Class/MakeMethods/Utility/TextBuilder.pm @@ -0,0 +1,207 @@ +package Class::MakeMethods::Utility::TextBuilder; + +$VERSION = 1.008; + +@EXPORT_OK = qw( text_builder ); +sub import { require Exporter and goto &Exporter::import } # lazy Exporter + +use strict; +use Carp; + +# $expanded_text = text_builder( $base_text, @exprs ) +sub text_builder { + my ( $text, @mod_exprs ) = @_; + + my @code_exprs; + while ( scalar @mod_exprs ) { + my $mod_expr = shift @mod_exprs; + if ( ref $mod_expr eq 'HASH' ) { + push @code_exprs, %$mod_expr; + } elsif ( ref $mod_expr eq 'ARRAY' ) { + unshift @mod_exprs, @$mod_expr; + } elsif ( ref $mod_expr eq 'CODE' ) { + $text = &$mod_expr( $text ); + } elsif ( ! ref $_ ) { + $mod_expr =~ s{\*}{$text}g; + $text = $mod_expr; + } else { + Carp::confess "Wierd contents of modifier array."; + } + } + my %rules = @code_exprs; + + my @exprs; + my @blocks; + foreach ( sort { length($b) <=> length($a) } keys %rules ) { + if ( s/\{\}\Z// ) { + push @blocks, $_; + } else { + push @exprs, $_; + } + } + push @blocks, 'UNUSED_CONSTANT' if ( ! scalar @blocks ); + push @exprs, 'UNUSED_CONSTANT' if ( ! scalar @exprs ); + + # There has *got* to be a better way to regex matched brackets... Right? + # Erm, well, no. It looks like Text::Balanced would do the trick, with the + # requirement that the below bit get re-written to not be regex-based. + my $expr_expr = '\b(' . join('|', map "\Q$_\E", @exprs ) . ')\b'; + my $block_expr = '\b(' . join('|', map "\Q$_\E", @blocks ) . ') \{ + ( [^\{\}]* + (?: \{ + [^\{\}]* + (?: \{ [^\{\}]* \} [^\{\}]* )*? + \} [^\{\}]* )*? + ) + \}'; + + 1 while ( + length $text and $text =~ s/ $expr_expr / + my $substitute = $rules{ $1 }; + if ( ! ref $substitute ) { + $substitute; + } elsif ( ref $substitute eq 'CODE' ) { + &{ $substitute }(); + } else { + croak "Unknown type of substitution rule: '$substitute'"; + } + /gesx or $text =~ s/ $block_expr / + my $substitute = $rules{ $1 . '{}' }; + my $contents = $2; + if ( ! ref $substitute ) { + $substitute =~ s{\*}{$contents}g; + $substitute; + } elsif ( ref $substitute eq 'HASH' ) { + $substitute->{$contents}; + } elsif ( ref $substitute eq 'CODE' ) { + &{ $substitute }( $contents ); + } else { + croak "Unknown type of substitution rule: '$substitute'"; + } + /gesx + ); + + return $text; +} + +1; + +__END__ + +=head1 NAME + +Class::MakeMethods::Utility::TextBuilder - Basic text substitutions + +=head1 SYNOPSIS + + print text_builder( $base_text, @exprs ) + +=head1 DESCRIPTION + +This module provides a single function, which implements a simple "text macro" mechanism for assembling templated text strings. + + $expanded_text = text_builder( $base_text, @exprs ) + +Returns a modified copy of $base_text using rules from the @exprs list. + +The @exprs list may contain any of the following: + +=over 4 + +=item * + +A string, in which any '*' characters will be replaced by the base text. The interpolated string then replaces the base text. + +=item * + +A code-ref, which will be called with the base text as its only argument. The result of that call then replaces the base text. + +=item * + +A hash-ref, which will be added to the substitution hash used in the second pass, below. + +=item * + +An array-ref, containing additional expressions to be treated as above. + +=back + +After any initial string and code-ref rules have been applied, the hash of substitution rules are applied. + +The text will be searched for occurances of the keys of the substitution hash, which will be modified based on the corresponding value in the hash. If the substitution key ends with '{}', the search will also match a balanced block of braces, and that value will also be used in the substitution. + +The hash-ref may contain the following types of rules: + +=over 4 + +=item * + +'string' => 'string' + +Occurances of the first string are to be replaced by the second. + +=item * + +'string' => I<code_ref> + +Occurances of the string are to be replaced by the results of calling the subroutine with no arguments. + +=item * + +'string{}' => 'string' + +Occurances of the first string and subsequent block of braces are replaced by a copy of the second string in which any '*' characters have first been replaced by the contents of the brace block. + +=item * + +'string{}' => I<code_ref> + +Occurances of the string and subsequent block of braces are replaced by the results of calling the subroutine with the contents of the brace block as its only argument. + +=item * + +'string{}' => I<hash_ref> + +Occurances of the string and subsequent block of braces are replaced by using the contents of the brace block as a key into the provided hash-ref. + +=back + +=head1 EXAMPLE + +The following text and modification rules provides a skeleton for a collection letter: + + my $letter = "You owe us AMOUNT. Please pay up!\n\n" . + "THREAT{SEVERITY}"; + + my @exprs = ( + "Dear NAMEm\n\n*", + "*\n\n-- The Management", + + { 'THREAT{}' => { 'good'=>'Please?', 'bad'=>'Or else!' } }, + + "\t\t\t\tDATE\n*", + { 'DATE' => 'Tuesday, April 1, 2001' }, + ); + +One might invoke this template by providing additional data for a given instance and calling the text_builder function: + + my $item = { 'NAME'=>'John', 'AMOUNT'=>'200 camels', 'SEVERITY'=>'bad' }; + + print text_builder( $letter, @exprs, $item ); + +The resulting output is shown below: + + Tuesday, April 1, 2001 + Dear John, + + You owe us 200 camels. Please pay up! + + Or else! + + -- The Management + +=head1 SEE ALSO + +See L<Class::MakeMethods> for general information about this distribution. + +=cut |
