]> git.donarmstrong.com Git - perltidy.git/blob - examples/filter_example.pl
55f545242c8b1f967e2b9de392fd57c246e5ff5b
[perltidy.git] / examples / filter_example.pl
1 #!/usr/bin/perl -w
2 use Perl::Tidy;
3
4 # Illustrate use of prefilter and postfilter parameters to perltidy.  
5 # This example program uses a prefilter it to convert the 'method'
6 # keyword to 'sub', and a postfilter to convert back, so that perltidy will
7 # work for Method::Signature::Simple code.  
8 # NOTE: This program illustrates the use of filters but has not been
9 # extensively tested.  
10
11 # usage:
12 #   perl filter_example.pl filter_example.in
13 #
14 # How it works:
15 # 1. First the prefilter changes lines beginning with 'method foo' to 'sub
16 # METHOD_foo'
17 # 2. Then perltidy formats the code
18 # 3. Then the postfilter changes 'sub METHOD_' to 'method ' everywhere.
19 # (This assumes that there are no methods named METHOD_*, and that the keyword
20 # method always begins a line in the input file).  
21 #
22 # Debugging hints: 
23 # 1. Try commenting out the postfilter and running with 
24 # the --notidy option to see what the prefilter alone is doing.
25 # 2. Then run with both pre- and post ters with --notidy to be sure
26 # that the postfilter properly undoes the prefilter.
27
28 my $arg_string = undef;
29 my $err=Perl::Tidy::perltidy(
30     argv => $arg_string,
31     prefilter =>
32       sub { $_ = $_[0]; s/^\s*method\s+(\w.*)/sub METHOD_$1/gm; return $_ },
33     postfilter =>
34       sub { $_ = $_[0]; s/sub\s+METHOD_/method /gm; return $_ }
35 );
36 if ($err) {
37     die "Error calling perltidy\n";
38 }
39 __END__
40
41 # Try running on the following code (file filter_example.in):
42
43 use Method::Signatures::Simple;
44
45  method foo { $self->bar }
46
47        # with signature
48     method foo($bar, %opts) { $self->bar(reverse $bar) if $opts{rev};
49     }
50
51     # attributes
52     method foo : lvalue { $self->{foo} 
53 }
54
55  # change invocant name
56     method 
57 foo ($class: $bar) { $class->bar($bar) }