OC-PM: EasySlice and Source Filters?

Wilson, Douglas dgwilson at sonomasystems.net
Thu Jan 9 16:57:37 CST 2003


It wasn't really brought up how namespaces were handled
with the EasySlice module, and since source filters were also
mentioned, so for the fun of it, I came up with this source filter
to allow something like '$object->foo:bar' and have 'foo:bar' be the method
name.
First is the demo script, then the module:
#!/usr/local/bin/perl

package Useless::Package;

use strict;
use warnings;
use vars qw($AUTOLOAD);

# Print the method name and arguments
# and just return the 'object'
sub AUTOLOAD {
  my $self = shift;
  $AUTOLOAD =~ /^(.*?)::(.*)/
   or die "Error autoloading $AUTOLOAD";
  print "$1->$2(@_)\n";
  $self;
}

package main;
use strict;
use warnings;
use MethodFilter;

Useless::Package->foo:orders("a".."c")
  ->baz:order("b".."d")->foo:bar(1..3);
###################################

package MethodFilter;
#
# Use methods with a single colon
# (":") character in them
# as bare words.
# Author: Douglas Wilson
#
# E.g. Package->foo:bar;
# creates lexical variable $_foo__bar,
# sets it to 'foo:bar', and substitutes the variable name
# into the method call
#
# Known issues:
# 1) $condtion ? $obj->method:function();
#    (just put white space around the ":" to fix it)
# 2) single quoted strings containing, e.g., '->word:word'
#    (break up the string: '->' . 'word:word')
# 3) Line break after method operator '->'
#    (break the line before the '->')
#
use strict;
use warnings;
use Filter::Util::Call;

sub filter {
  my ($self) = @_;
  my ($status);

  if ( ( $status = filter_read() ) > 0 ) {
    s/(?<=->)((\w+):(\w+))
      (?{$self->{methods}->{$1} = "\$_${2}__${3}"})
     /\$_${2}__${3}/gx;
    $self->{buffer} .= $_;
    $_ = '';
  } elsif (%$self) {    # EOF
    $_ = 'my ('
      . join ( ",", values %{ $self->{methods} } )
      . ")=qw(@{[keys %{$self->{methods}}]});";
    $_ .= $self->{buffer};
    $status = 1;
    %$self  = ();
  } else {
    $_ = $self->{buffer};
  }

  $status;
}

sub import {
  filter_add( { methods => {}, buffer => '' } );
}

1;



More information about the Oc-pm mailing list