Upgrade to Module-Build-0.2808
[p5sagit/p5-mst-13.2.git] / lib / Tie / Hash / NamedCapture.pm
1 package Tie::Hash::NamedCapture;
2
3 use strict;
4 use warnings;
5
6 our $VERSION = "0.05";
7
8 sub TIEHASH {
9     my $classname = shift;
10     my %opts = @_;
11
12     my $self = bless { all => $opts{all} }, $classname;
13     return $self;
14 }
15
16 sub FETCH {
17     return re::regname($_[1],$_[0]->{all});
18 }
19
20 sub STORE {
21     require Carp;
22     Carp::croak("STORE forbidden: hashes tied to ",__PACKAGE__," are read-only.");
23 }
24
25 sub FIRSTKEY {
26     re::regnames_iterinit();
27     return $_[0]->NEXTKEY;
28 }
29
30 sub NEXTKEY {
31     return re::regnames_iternext($_[0]->{all});
32 }
33
34 sub EXISTS {
35     return defined re::regname( $_[1], $_[0]->{all});
36 }
37
38 sub DELETE {
39     require Carp;
40     Carp::croak("DELETE forbidden: hashes tied to ",__PACKAGE__," are read-only");
41 }
42
43 sub CLEAR {
44     require Carp;
45     Carp::croak("CLEAR forbidden: hashes tied to ",__PACKAGE__," are read-only");
46 }
47
48 sub SCALAR {
49     return scalar re::regnames($_[0]->{all});
50 }
51
52 tie %+, __PACKAGE__;
53 tie %-, __PACKAGE__, all => 1;
54
55 1;
56
57 __END__
58
59 =head1 NAME
60
61 Tie::Hash::NamedCapture - Named regexp capture buffers
62
63 =head1 SYNOPSIS
64
65     tie my %hash, "Tie::Hash::NamedCapture";
66     # %hash now behaves like %+
67
68     tie my %hash, "Tie::Hash::NamedCapture", all => 1;
69     # %hash now access buffers from regexp in $qr like %-
70
71 =head1 DESCRIPTION
72
73 This module is used to implement the special hashes C<%+> and C<%->, but it
74 can be used to tie other variables as you choose.
75
76 When the C<all> parameter is provided, then the tied hash elements will be
77 array refs listing the contents of each capture buffer whose name is the
78 same as the associated hash key. If none of these buffers were involved in
79 the match, the contents of that array ref will be as many C<undef> values
80 as there are capture buffers with that name. In other words, the tied hash
81 will behave as C<%->.
82
83 When the C<all> parameter is omitted or false, then the tied hash elements
84 will be the contents of the leftmost defined buffer with the name of the
85 associated hash key. In other words, the tied hash will behave as
86 C<%+>.
87
88 The keys of C<%->-like hashes correspond to all buffer names found in the
89 regular expression; the keys of C<%+>-like hashes list only the names of
90 buffers that have captured (and that are thus associated to defined values).
91
92 =head1 SEE ALSO
93
94 L<re>, L<perlmodlib/Pragmatic Modules>, L<perlvar/"%+">, L<perlvar/"%-">.
95
96 =cut