<...>
):keepall
Synopsis 5: Rules
Damian Conway <damian [at] conway.org> and Allison Randal <al [at] shadowed.net>
Maintainer: Patrick Michaud <pmichaud [at] pobox.com> Date: 24 Jun 2002 Last Modified: 25 Feb 2006 Number: 5 Version: 12
This document summarizes Apocalypse 5, which is about the new regex syntax. We now try to call them "rules" because they haven't been regular expressions for a long time. (The term "regex" is still acceptable.)
このドキュメントは、新たな正規表現構文(regex syntax)について述べている 黙示録(Apocalypse) 5の 要約です。私たちはそれを"ルール"と呼ぼうと考えています。なぜなら、 ながきに渡りそれはもはや正規表現ではないからです("regex"という言葉は 今でも受け入れられます)。
訳者注: ドキュメントはさらに新しくなっています (2006/4/13時点で Version 15)。 大きな変更はないようですが、 正確を期するなら オリジナル も参照してください。
The underlying match state object is now available as the $/
variable, which is implicitly lexically scoped. All access to the
current (or most recent) match is through this variable, even when
it doesn't look like it. The individual capture variables (such as $0
,
$1
, etc.) are just elements of $/
.
基礎をなすマッチ状態オブジェクトは、 <$/>という変数として 扱うことが可能となりました。これは暗黙裡にレキシカルスコープを持ちます。 カレントの(あるいは至近の)マッチに対するすべてのアクセスは、 たとえそうは見えなかったときでも、この変数を通してなされます。 $0, $1などの独立した捕獲変数(caputure vairables)は、 マッチした文字列全体である$/の単なる要素です。
By the way, the numbered capture variables now start at $0
, $1
,
$2
, etc. See below.
ところで、数字付けされた捕獲変数は$0
, $1
, $2
…のようになりました。
詳しくは後述します。
The following regex features use the same syntax as in Perl 5:
以下の正規表現機能はPerl 5における構文と同じものを使います:
Capturing: (...) キャプチャリング: (...)
Repetition quantifiers: *, +, and ? 繰り返し量指定子: *, +, ?
Alternatives: | 選択: |
Backslash escape: \
バックスラッシュエスケープ: \
Minimal matching suffix: ??, *?, +?
最小マッチング接尾辞: ??, *?, +?
The extended syntax (/x
) is no longer required...it's the default.
拡張構文(/x
)はデフォルトの動作となったので
もはや必要なくなりました。
There are no /s
or /m
modifiers (changes to the meta-characters
replace them - see below).
修飾子の/s
と
/m
はありません
(これらを置き換えるメタキャラクタができました。後述)。
There is no /e
evaluation modifier on substitutions; instead use:
置換において/e
という評価修飾子はありません。
代わりに以下のようにします:
s/pattern/{ code() }/
Modifiers are now placed as adverbs at the start of a match/substitution:
修飾子はマッチや置換の先頭に置かれるようになりました:
m:g:i/\s* (\w*) \s* ,?/;
Every modifier must start with its own colon. The delimiter must be separated from the final modifier by a colon or whitespace if it would be taken as an argument to the preceding modifier.
各修飾子はそれぞれコロンで始まっていなければなりません。 先行する修飾子の引数として扱われる可能性がある場合、 デリミタはコロンか空白によって最後の修飾子と区別がつくようになっていなければ なりません。
The single-character modifiers also have longer versions:
一文字の修飾子は長い名前も持っています:
:i :ignorecase :g :global
The :c
(or :continue
) modifier causes the pattern to continue
scanning from the string's current .pos
:
:c
修飾子(と:continue
修飾子)は
文字列のカレントの.pos
から
走査を継続するようにします:
m:c/ pattern / # start at end of # previous match on $_
Note that this does not automatically anchor the pattern to the starting
location. (Use :p
for that.) The pattern you supply to split
has an implicit :c
modifier.
本修飾子はパターンに対して自動的に開始位置を結びつけることはしないことに
注意してください(それを行うには:p
を使います)。
split
に渡したパターンは
暗黙のうちに:c
修飾子を持ちます。
The :p
(or :pos
) modifier causes the pattern to try to match only at
the string's current .pos
:
:p
(または:pos
)という修飾子は文字列の
カレントの .pos
においてのみ
マッチを試みます。
m:p/ pattern / # match at end of # previous match on $_
Since this is implicitly anchored to the position, it's suitable for
building parsers and lexers. The pattern you supply to a Perl macro's
"is parsed" trait has an implicit :p
modifier.
これはその位置に暗黙のうちに結び付けられる(anchored)ので、
パーサーやレクサを構築するのに好都合です。Perlマクロに対して渡された
パターンは暗黙裡に :p
修飾子が
つけられたものとして解析されます。
Note that
m:c/pattern/
is roughly equivalent to
これは以下のものとほぼ同じであることに注意してください。
m:p/.*? pattern/
The new :once
modifier replaces the Perl 5 ?...?
syntax:
あらたな:once
修飾子は、Perl5の?...?
構文を置き換えます:
m:once/ pattern / # 最初の一回だけマッチする
[Note: We're still not sure if :w is ultimately going to work exactly as described below. But this is how it works for now.]
The new :w
(:words
) modifier causes whitespace sequences to be
replaced by \s*
or \s+
subpattern as defined by the <?ws>
rule.
新たな:w
(:words
) 修飾子は
空白の並びを
<?ws>
ルールで定義されているように
\s*
サブパターンもしくは
\s+
サブパターンで
置き換えます。
m:w/ next cmd = <condition>/
Same as:
m/ <?ws> next <?ws> cmd <?ws> = <?ws> <condition>/
which is effectively the same as:
これは以下のものと同じことです:
m/ \s* next \s+ cmd \s* = \s* <condition>/
But in the case of
しかし、
m:w { (a|\*) (b|\+) }
or equivalently,
や、これと等価な
m { (a|\*) <?ws> (b|\+) }
<?ws>
can't decide what to do until it sees the data. It still does
the right thing. If not, define your own <?ws>
and :w
will use that.
の場合、<?ws>
は
データを見るまではどのように振舞うかを決定することができません。
それはまだ正しいことをしています。もしそうでないなら、
あなた自身の<?ws>
と
:w
を定義してそれを使うことになるでしょう。
New modifiers specify Unicode level:
Unicodeのレベルを指定する新しい修飾子:
m:bytes / .**{2} / # 2バイトにマッチ m:codes / .**{2} / # 2つのコードポイントにマッチ m:graphs/ .**{2} / # 2つの graphemes にマッチ m:langs / .**{2} / # 2つの(言語依存の)キャラクタにマッチ
There are corresponding pragmas to default to these levels.
これらのレベルをデフォルトにするプラグマがあります。
The new :perl5
modifier allows Perl 5 regex syntax to be used instead:
新たな:perl5
修飾子は
Perl 5の正規表現構文を使うことを許可します:
m:perl5/(?mi)^[a-z]{1,2}(?=\s)/
(It does not go so far as to allow you to put your modifiers at the end.)
(ただし修飾子を末尾に置くことはできません)
Any integer modifier specifies a count. What kind of count is determined by the character that follows.
任意の整数の修飾子は回数を指定します。回数が指定する種類は 整数に後続するキャラクタによって決定されます。
If followed by an x
, it means repetition. Use :x(4)
for the
general form. So
x
が後続していた場合、それは繰り返しを意味します。
一般的な形式では:x(4)
を使います。したがって
s:4x { (<?ident>) = (\N+) $$}{$0 => $1};
is the same as:
これは以下のものと同じです:
s:x(4) { (<?ident>) = (\N+) $$}{$0 => $1};
which is almost the same as:
また、以下のものともほぼ同じことです:
$_.pos = 0; s:c{ (<?ident>) = (\N+) $$}{$0 => $1} for 1..4;
except that the string is unchanged unless all four matches are found.
However, ranges are allowed, so you can say :x(1..4)
to change anywhere
from one to four matches.
ただし、前者の場合にはマッチを四回見つけるまでは文字列の変更が
なされないという点が異なります。しかし、範囲を指定することができるので、
一回から四回のマッチのそれぞれで変更することを
:x(1..4)
と指定することができます・
If the number is followed by an st
, nd
, rd
, or th
, it means
find the Nth occurrence. Use :nth(3)
for the general form. So
数値の後ろに
st
,
nd
,
rd
,
th
が
続いていた場合、それはN番目の出現を意味します。
一般的な形式には:nth(3)
を使います。
したがって、
s:3rd/(\d+)/@data[$0]/;
is the same as
は以下のものと同じです
s:nth(3)/(\d+)/@data[$0]/;
which is the same as:
また、以下のものとも同じ意味です:
m/(\d+)/ && m:c/(\d+)/ && s:c/(\d+)/@data[$0]/;
Lists and junctions are allowed: :nth(1|2|3|5|8|13|21|34|55|89)
.
リストとjunctionを使うことができます:
:nth(1|2|3|5|8|13|21|34|55|89)
.
So are closures: :nth{.is_fibonacci}
クロージャも使えます: :nth{.is_fibonacci}
With the new :ov
(:overlap
) modifier, the current rule will
match at all possible character positions (including overlapping)
and return all matches in a list context, or a disjunction of matches
in a scalar context. The first match at any position is returned.
新しい修飾子:ov
(:overlap
)を使うことによって、
カレントのルールがすべての可能なキャラクタ位置にマッチするようになります。
リストコンテキストではすべてのマッチしたものが返り、
スカラーコンテキストではマッチのdisjunction(分離、分裂)が返ります。
任意の場所の最初のマッチが返されます。
$str = "abracadabra";
if $str ~~ m:overlap/ a (.*) a / { @substrings = $/.matches(); # bracadabr cadabr dabr br }
With the new :ex
(:exhaustive
) modifier, the current rule will match
every possible way (including overlapping) and return all matches in a list
context, or a disjunction of matches in a scalar context.
新たな修飾子 :ex
(:exhaustive
exhausteve = 徹底的)
を使うことによって、カレントのルールは可能なオーバーラップするものも
含めて組み合わせすべてにマッチして、リストコンテキストではすべての
マッチしたものを返し、スカラーコンテキストではマッチのdisjunctionを
返します。
$str = "abracadabra";
if $str ~~ m:exhaustive/ a (.*) a / { @substrings = $/.matches(); # br brac bracad bracadabr # c cad cadabr d dabr br }
The new :rw
modifier causes this rule to "claim" the current
string for modification rather than assuming copy-on-write semantics.
All the bindings in $/
become lvalues into the string, such
that if you modify, say, $1
, the original string is modified in
that location, and the positions of all the other fields modified
accordingly (whatever that means). In the absence of this modifier
(especially if it isn't implemented yet, or is never implemented),
all pieces of $/
are considered copy-on-write, if not read-only.
新しい修飾子 :rw
は
そのルールに対して、copy-on-write セマンティクスではなく
カレントの文字列に対して変更を行うことを“主張”します。
$/
の中で束縛されているすべてのものは
lvalueから文字列となり、もし例えば$1
を変更したときには下の文字列の対応する場所が変更されて、
それにしたがって他のすべてのフィールドの位置が変更されます。
本修飾子がなければ(とくにまだ実装されていなかったりしたなら)、
$/
のすべての要素は
read-only でない場合には copy-on-write とみなされます。
The new :keepall
modifier causes this rule and all invoked subrules
to remember everything, even if the rules themselves don't ask for
their subrules to be remembered. This is for forcing a grammar that
throws away whitespace and comments to keep them instead.
新しい修飾子 :keepall
は
そのルールと、呼び出したすべてのサブルールに対して
ルール自身がそのサブルールに対して記憶することを指示していなくても
すべてを記憶するようにします。本修飾子は文法に対して
空白やコメントを捨て去るのではなくて保存しておくように強制します。
The :i
, :w
, :perl5
, and Unicode-level modifiers can be
placed inside the rule (and are lexically scoped):
:i
, :w
, :perl5
といった修飾子ととUnicodeレベル修飾子は
ルールの内側におくことができます(レキシカルスコープを持ちます):
m/:w alignment = [:i left|right|cent[er|re]] /
User-defined modifiers will be possible:
ユーザーが修飾子を定義することもできます:
m:fuzzy/pattern/;
User-defined modifiers can also take arguments:
ユーザー定義の修飾子は引数をとることもできます:
m:fuzzy('bare')/pattern/;
To use parens or brackets for your delimiters you have to separate:
括弧やブラケットをデリミタとして使うには分割する必要があります:
m:fuzzy (pattern); m:fuzzy:(pattern);
or you'll end up with:
m:fuzzy(fuzzyargs); pattern ;
A dot .
now matches any character including newline. (The /s
modifier is gone.)
ドット演算子.
は改行を含めた
すべてのキャラクタにマッチするようになりました
(/s
修飾子はなくなりました)。
^
and $
now always match the start/end of a string, like the
old \A
and \z
. (The /m
modifier is gone.)
^
と $
は以前の
\A
や \z
と同様に常に文字列の先頭/末尾にマッチするようになりました
(/m
修飾子はなくなりました)。
A $
no longer matches an optional preceding \n
so it's necessary
to say \n?$
if that's what you mean.
$
は先行する(省略可能な)
\n
にマッチしなくなったので、
そのような動作を必要とするならば\n?$
とする必要があります。
\n
now matches a logical (platform independent) newline not just \x0a
.
\n
は、単なる\x0a
ではなくて、論理的な(プラットフォーム独立な)
改行にマッチするようになりました。
The \A
, \Z
, and \z
metacharacters are gone.
メタキャラクタの
\A
,
\Z
,
\z
はなくなりました。
Because /x
is default:
/x
がデフォルトになったので:
An unescaped #
now always introduces a comment.
#
は常にコメントの始まりになります。
Whitespace is now always metasyntactic, i.e. used only for layout
and not matched literally (but see the :w
modifier described above).
空白は常にmetasyntacticになりました。つまりレイアウトのためにのみ用いられ、
リテラルとしてマッチすることはありません(ただし前述した
:w
修飾子を参照してください)。
^^
and $$
match line beginnings and endings. (The /m
modifier is gone.) They are both zero-width assertions. $$
matches before any \n
(logical newline), and also at the end of
the string if the final character was not a \n
. ^^
always
matches the beginning of the string and after any \n
that is not
the final character in the string.
^^
と
$$
はそれぞれ行の先頭と末尾にマッチします
(/m
修飾子はなくなりました)。
これらは両方とも幅を持たない(zero-width)の表明です。
$$
は \n
(論理的な改行)の前にマッチしますが、文字列の末尾のキャラクタが
\n
でない場合には
文字列の末尾にマッチします。
^^
は
文字列の中にある(ただし文字列の最後のキャラクタではない)
\n
の直後にマッチします。
.
matches an "anything" while \N
matches an "anything except
newline" (The /s
modifier is gone.) In particular, \N
matches
neither carriage return nor line feed.
.
はすべての“任意の”キャラクタにマッチします。
それに対して\N
は“改行を除く任意のキャラクタ”にマッチします
(/s
修飾子はなくなりました)。
特に、\N
はキャリッジリターンにもラインフィードにもマッチしません。
The new &
metacharacter separates conjunctive terms. The patterns on
either side must match with the same beginning and end point. The
operator is list associative like |
, has higher precedence than |
,
and backtracking makes the right argument vary faster than the left.
新しいメタキャラクタ &
は
conjunctive terms (接続語?)を分割します。
このメタキャラクタの両側にあるパターンのそれぞれは
同じ開始位置と同じ終了位置にマッチしなければなりません。
この演算子は |
と同様に
list associativeで、バックトラッキングは
左の引数より早く右の引数を作ります。
(...)
still delimits a capturing group. However the ordering of these
groups is hierarchical, rather than linear. See Nested subpattern captures.
(...)
は今でも捕獲グループを区切りますが、
捕獲したグループの順序付けは階層的であって、線形ではありません。
Nested subpattern capturesを参照してください。
[...]
is no longer a character class.
It now delimits a non-capturing group.
[...]
はもはやキャラクタクラスではなくなりました。
現在では捕獲を行わないグループを区切ります。
{...}
is no longer a repetition quantifier.
It now delimits an embedded closure.
{...}
は量指定子ではなくなりました。
現在では埋め込みのクロージャを区切ります。
You can call Perl code as part of a rule match by using a closure. Embedded code does not usually affect the match--it is only used for side-effects:
クロージャを使って、ルールの一部としてPerlのプログラム片を 呼び出すことができます。埋め込まれたプログラム片は通常のマッチの 効果をもたず、その副作用のみが使われます:
/ (\S+) { print "string not blank\n"; $text = $0; }
\s+ { print "but does contain whitespace\n" }
/
It can affect the match if it calls fail
:
fail
を呼び出した場合にはマッチングに影響を及ぼすこともできます:
/ (\d+) { $0 < 256 or fail } /
Closures are guaranteed to be called at the canonical time even if the optimizer could prove that something after them can't match. (Anything before is fair game, however.)
クロージャは、オプティマイザが(クロージャの後に続くものが) マッチしないことを見つけ出したときであっても 正しいときに呼び出されることが保証されます。
The repetition specifier is now **{...}
for maximal matching,
with a corresponding **{...}?
for minimal matching. Space is
allowed on either side of the asterisks. The curlies are taken to
be a closure returning a number or a range.
最大マッチングを表す繰り返し指定子は**{...}
のようになりました。
最小マッチの指定は**{...}?
です。
スペースをアスタリスクの両側のどちらにも置くことができます。
カーリーブレースは数値か範囲を返すクロージャとして扱われます。
/ value was (\d ** {1..6}?) with ([\w]**{$m..$n}) /
It is illegal to return a list, so this easy mistake fails:
以下のものはリストを返す不正なものなので、このありがちな間違いは失敗します:
/ [foo]**{1,3} /
(At least, it fails in the absence of "use rx :listquantifier
"
which is likely to be unimplemented in Perl 6.0.0 anyway).
(少なくともこれは、Perl 6.0.0 では実装されないであろう
"use rx :listquantifier
"がないので失敗します)
The optimizer will likely optimize away things like **{1...}
so that the closure is never actually run in that case. But it's
a closure that must be run in the general case, so you can use
it to generate a range on the fly based on the earlier matching.
(Of course, bear in mind the closure is run before attempting to
match whatever it quantifies.)
オプティマイザは**{1...}
のようなものを最適化してしまうので、
このようなクロージャは実際にはこのケースにおいて呼ばれることはありません。
しかし、一般的な場合においてはクロージャは実行されなければならないものです。
ですから、先行するマッチングに基づいてその場で範囲を生成するような
目的のためにクロージャを使うことができます
(もちろん、マッチに対して数量子を適用するより前にクロージャが
実行されることを覚えておいてください)。
<...>
are now extensible metasyntax delimiters or "assertions"
(i.e. they replace Perl 5's crufty (?...)
syntax).
<...>
は拡張可能なメタ構文区切り子もしくは“表明”となりました
(Perl 5の(?...)
構文を置き換えます)。
In Perl 6 rules, variables don't interpolate.
Perl 6のルールでは、変数は展開されません。
Instead they're passed "raw" to the rule engine, which can then decide how to handle them (more on that below).
どのように扱うかをルールエンジンが決めることができるように、 変数は“生のまま”ルールエンジンに渡されます。
The default way in which the engine handles a scalar is to match it
as a <'...'>
literal (i.e. it does not treat the interpolated string
as a subpattern). In other words, a Perl 6:
エンジンがスカラーを取り扱うデフォルトの方法は、
'...'
リテラル
としてマッチングを行うというものです
(展開された文字列をサブパターンとしては取り扱いません)。
言い換えると、Perl 6では:
/ $var /
is like a Perl 5:
は、Perl 5での以下のものと同じです:
/ \Q$var\E /
(To get rule interpolation use an assertion - see below)
(ルールの展開をするには表明を使います - 後述)
An interpolated array:
展開された配列:
/ @cmds /
is matched as if it were an alternation of its elements:
これはその要素を選択で結んだかのようにマッチングを行います:
/ [ @cmds[0] | @cmds[1] | @cmds[2] | ... ] /
As with a scalar variable, each element is matched as a literal.
スカラー変数がそうであるように、要素のそれぞれはリテラルとして マッチングします。
An interpolated hash matches the longest possible key of the hash
as a literal, or fails if no key matches. (A ""
key
will match anywhere, provided no longer key matches.)
展開されたハッシュはリテラルとして最も長いハッシュのキーにマッチします。
マッチするキーがない場合には失敗します
(""
キーはどこにでもマッチします)。
If the corresponding value of the hash element is a closure, it is executed.
対応するハッシュの要素がクロージャである場合にはそれが実行されます。
If it is a string or rule object, it is executed as a subrule.
対応するハッシュの要素が 文字列かルールオブジェクトである場合にはそれがサブルールであるとして実行されます。
If it has the value 1, nothing special happens beyond the match.
1という値を持っていた場合にはマッチに関して特別なことは行いません。
Any other value causes the match to fail.
その他の値はマッチを失敗させます。
<...>
)The first character after <
determines the behaviour of the assertion.
<
の直後のキャラクタはその表明の振る舞いを決定します。
A leading alphabetic character means it's a capturing grammatical assertion (i.e. a subrule or a named character class - see below):
アルファベットで始まる場合には、それが文法的な表明 (サブパターンもしくは名前付キャラクタクラス - 後述) であることを意味します:
/ <sign>? <mantissa> <exponent>? /
The special named assertions include:
特殊な名前付き表明には以下のものが含まれます:
/ <before pattern> / # 以前は /(?=pattern)/ でした / <after pattern> / # 以前は /(?<pattern)/ でした
/ <ws> / # :w ルールによって空白にマッチ
/ <sp> / # スペースキャラクタにマッチ
The after
assertion implements lookbehind by reversing the syntax
tree and looking for things in the opposite order going to the left.
It is illegal to do lookbehind on a pattern that cannot be reversed.
after
表明は構文木を逆転することによって戻り読み(後読み)を実装していて、
左側に向かって逆向きに検索を行います。逆転することのできない
パターンを後読みで使うことは許されません。
A leading ?
causes the assertion not to capture what it matches (see
Subrule captures. For example:
先行する ?
はその表明がマッチしたものを捕獲しません
(Subrule capturesを参照)。例を挙げましょう:
/ <ident> <ws> / # $/<ident> と $/<ws> の両方が捕獲される / <?ident> <ws> / # $/<ws> だけが捕獲される / <?ident> <?ws> / # 捕獲されるものはない
A leading $
indicates an indirect rule. The variable must contain
either a hard reference to a rule, or a string containing the rule.
先行する$
は間接ルールを表します。
その変数はルールへのハードリファレンスか、ルールを構成する文字列の
いずれかを保持していなくてはなりません。
A leading ::
indicates a symbolic indirect rule:
先行する ::
は
シンボリックな間接ルールを表します:
/ <::($somename)>
The variable must contain the name of a rule.
ここで変数はルールの名前を保持していなくてはなりません。
A leading @
matches like a bare array except that each element
is treated as a rule (string or hard ref) rather than as a literal.
先行する @
は裸の配列と同じようにマッチしますが、
各要素がリテラルとしてではなくルール
(文字列もしくはハードリファレンス)として扱われる点が異なります。
A leading %
matches like a bare hash except that each key
is treated as a rule (string or hard ref) rather than as a literal.
先行する %
は裸のハッシュと同じようにマッチしますが、
各キーがリテラルとしてではなく
ルール(文字列もしくはハードリファレンス)として扱われる点が異なります。
A leading {
indicates code that produces a rule to be interpolated
into the pattern at that point:
先行する {
はその場所で
パターンとして展開されてルールを生成するコードを表します:
/ (<?ident>) <{ %cache{$0} //= get_body($0) }> /
The closure is guaranteed to be run at the canonical time.
このクロージャは正しいタイミングで実行されます。
A leading &
interpolates the return value of a subroutine call as
a rule. Hence
先行する&
は
サブルーチンの戻り値がルールとして展開されます。したがって
<&foo()>
is short for
これは以下の短縮記法です
<{ foo() }>
In any case of rule interpolation, if the value already happens to be
a rule object, it is not recompiled. If it is a string, the compiled
form is cached with the string so that it is not recompiled next
time you use it unless the string changes. (Any external lexical
variable names must be rebound each time though.) Rules may not be
interpolated with unbalanced bracketing. An interpolated subrule
keeps its own inner $/
, so its parentheses never count toward the
outer rules groupings. (In other words, parenthesis numbering is always
lexically scoped.)
ルール展開のいずれのケースにおいても、その値がすでにルールオブジェクトとして
存在していたならば再コンパイルされることはありません。
もしそれが文字列であれば、コンパイル済み形式のものはその文字列と共に
キャッシングされるので、文字列を変更しない限りは次にその文字列を使った
ときに再コンパイルされることはありません(ただしレキシカル変数の名前は
使われるたびごとに束縛されます)。ルールはバランスの取れていない
括弧によって展開されることはありません。展開されたサブルールは
固有の $/
を持ち、したがって
その括弧は外側のルールによってグルーピングとして数えられることは
決してありません(言い換えれば、括弧による番号付けは常にレキシカルスコープ
であるということです)。
A leading ?{
or !{
indicates a code assertion:
先行する ?{
や !{
はコード表明 (code assertion) を表します:
/ (\d**{1..3}) <?{ $0 < 256 }> / / (\d**{1..3}) <!{ $0 < 256 }> /
Similar to:
これは以下のものと同じです:
/ (\d**{1..3}) { $0 < 256 or fail } / / (\d**{1..3}) { $0 < 256 and fail } /
Unlike closures, code assertions are not guaranteed to be run at the canonical time if the optimizer can prove something later can't match. So you can sneak in a call to a non-canonical closure that way:
クロージャとは異なり、コード表明はオプティマイザが後の方で マッチできない何かを見つけ出したときには正しいタイミングで 実行時に呼ばれません。そのため、呼び出しにおいて非正準クロージャ (non-canonical closure)をsneakすることができます:
/^foo .* <?{ do { say "Got here!" } or 1 }> .* bar$/
The do
block is unlikely to run unless the string ends with "bar
ɮ
このdo
ブロックは
"bar
ɠで終わる文字列がない限り
呼び出されることはありません。
A leading (
indicates the start of a result capture:
先行する (
は結果の捕捉の開始を表します:
/ foo <( \d+ )> bar /
is equivalent to:
これは以下のものと等価です:
/ <after foo> \d+ <before bar> /
except that the scan for "foo" can be done in the forward direction,
while a lookbehind assertion would presumably scan for \d+ and then
match "foo" backwards. The use of <(...)>
affects only the
meaning of the "result object" and the positions of the beginning and
ending of the match. That is, after the match above, $()
contains
only the digits matched, and .pos
is pointing to after the digits.
Other captures (named or numbered) are unaffected and may be accessed
through $/
.
ただし、前者の走査が前方(文字列の末尾)に向かって行われるのに
対し、戻り読み表明では最初に \d+ を探してから“foo”を後ろ向き
(文字列の先頭)に向かって探していく点が異なります。
<(...)>
を使った効果は“結果オブジェクト”と
マッチ結果の開始位置/終了位置にのみ影響します。
つまり、マッチを行った後の時点で$()
はマッチした数字のみを
保持していて、また、.pos
は数字列の後を指しているということです。
その他の捕獲(名前によるものにしろ数字によるものにしろ)は
影響を受けず、$/
を通じてアクセスすることができます。
A leading [
or +
indicates an enumerated character class. Ranges
in enumerated character classes are indicated with ..
.
先行する [
と +
は列挙型キャラクタクラスを表します。
列挙型キャラクタクラスにおける範囲は ..
で表します。
/ <[a..z_]>* / / <+[a..z_]>* /
A leading -
indicates a complemented character class:
先行する -
はキャラクタクラスの捕集合をあらわします:
/ <-[a..z_]> <-alpha> /
Character classes can be combined (additively or subtractively) within a single set of angle brackets. For example:
キャラクタクラスは一つのアングルブラケットの中で (加算や減算を行うために)組み合わせることができます。 例を挙げましょう:
/ <[a..z]-[aeiou]+xdigit> / # consonant or hex digit
If such a combination starts with a named character class, a leading
+
is required:
もし名前つきクラスによってそのような組み合わせが始まっているのであれば、
先頭に+
が必要になります。
/ <+alpha-[Jj]> / # J-less alpha
A leading '
indicates a literal match (including whitespace):
先行する '
は空白も含めてリテラルとしてマッチすること表します:
/ <'match this exactly (whitespace matters)'> /
A leading "
indicates a literal match after interpolation:
先行する "
は展開した後で文字通りにマッチすることを表します:
/ <"match $THIS exactly (whitespace still matters)"> /
The special assertion <.>
matches any logical grapheme
(including a Unicode combining character sequences):
特殊な表明 <.>
は
論理的なgraphme(Unicodeの結合キャラクタシーケンスも含む)にマッチします:
/ seekto = <.> / # Maybe a combined char
Same as:
これは以下と同じです:
/ seekto = [:graphs .] /
A leading !
indicates a negated meaning (always a zero-width assertion):
先行する !
は意味を逆転します(常に幅を持たない):
/ <!before _ > / # We aren't before an _
The \p
and \P
properties become intrinsic grammar rules
(<prop ...>
and <!prop ...>
).
プロパティ\p
と \P
は本質的な文法ルール
(<prop ...>
と
<!prop ...>
)
になりました。
The \L...\E
, \U...\E
, and \Q...\E
sequences are gone. In the
rare cases that need them you can use <{ lc $rule }>
etc.
\L...\E
, \U...\E
, \Q...\E
といったシーケンスはなくなりました。
それが必要となる場合には <{ lc $rule }>
などを使うことができます。
The \G
sequence is gone. Use :p
instead. (Note, however, that
it makes no sense to use :p
within a pattern, since every internal
pattern is implicitly anchored to the current position. You'll have
to explicitly compare <( .pos == $oldpos )>
in that case.)
\G
というシーケンスはなくなりました。
代わりに :p
を使います
(しかしながら、パターンの中で :p
を使うことは、内部的なパターンが暗黙裡にカレント位置に結び付けられるので
意味がないということに注意してください。そのような場合
<( .pos == $oldpos )>
とする必要があるでしょう)。
Backreferences (e.g. \1
, \2
, etc.) are gone; $0
, $1
, etc. can be
used instead, because variables are no longer interpolated.
\1
, \2
, ...のような後方参照はなくなりました。
変数が展開されないようになったので$0
, $1
, ...を代わりに使うことができます。
New backslash sequences, \h
and \v
, match horizontal and vertical
whitespace respectively, including Unicode.
新しいバックスラッシュシーケンス
\h
と
\v
はそれぞれ
水平的な空白と垂直的な空白にマッチします(Unicodeを含む)。
\s
now matches any Unicode whitespace character.
\s
はUnicodeの空白キャラクタにマッチするようになりました。
The new backslash sequence \N
matches anything except a logical
newline; it is the negation of \n
.
新しいバックスラッシュシーケンス \N
は論理的な改行以外の任意のものにマッチします。これは
\n
の否定形です。
A series of other new capital backslash sequences are also the negation of their lower-case counterparts:
その他の大文字のバックスラッシュシーケンスはその小文字バージョンの ものの否定形です:
\H
matches anything but horizontal whitespace.
\H
は水平的な空白以外の任意のものにマッチします。
\V
matches anything but vertical whitespace.
\V
は垂直的な空白以外の任意のものにマッチします。
\T
matches anything but a tab.
\T
はタブ以外のものにマッチします。
\R
matches anything but a return.
\R
はリターン以外のものにマッチします。
\F
matches anything but a formfeed.
\F
は改ページ以外のものにマッチします。
\E
matches anything but an escape.
\E
はエスケープ以外のものにマッチします。
\X...
matches anything but the specified character (specified in
hexadecimal).
\X...
は十六進指定されたキャラクタ以外の任意のものにマッチします
The Perl 5 qr/pattern/
regex constructor is gone.
Perl 5のqr/pattern/
という正規表現構築子はなくなりました。
The Perl 6 equivalents are:
Perl 6では以下のようになります:
rule { pattern } # 常に { と } を区切りとする rx / pattern / # ほとんどすべてのキャラクタを区切りとすることができる
You may not use whitespace or alphanumerics for delimiters. Space is
optional unless needed to distinguish from modifier arguments or
function parens. So you may use parens as your rx
delimiters,
but only if you interpose a colon or whitespace:
区切りとして空白、アルファベット、数字を使うことはできません。
スペースは修飾子の引数や関数の括弧と区別する必要がなければ
省略することができます。ですから、
括弧を rx
の区切りとして使うことはできるのですが、
それはコロンや空白を置いたときだけです。
rx:( pattern ) # okay rx ( pattern ) # okay rx( 1,2,3 ) # 関数 rxを呼び出そうとする
If either form needs modifiers, they go before the opening delimiter:
いずれの形式においても修飾子が必要な場合には 開きの区切り子の前に修飾子を置きます。
$rule = rule :g:w:i { my name is (.*) }; $rule = rx:g:w:i / my name is (.*) /;
Space or colon is necessary after the final modifer if you use any bracketing character for the delimiter. (Otherwise it would be taken as an argument to the modifier.)
区切り子として括弧類を使う場合には最後の修飾子の後に スペースかコロンが必要です(省略した場合には修飾子の 引数として扱われてしまいます)。
You may not use colons for the delimiter. Space is allowed between modifiers:
コロンを区切りとすることはできません。 修飾子の間にスペースを置くことができます。
$rule = rx :g :w :i / my name is (.*) /;
The name of the constructor was changed from qr
because it's no
longer an interpolating quote-like operator. rx
stands for Ȳule
expressionɬ or occasionally Ȳegexɮ :-)
もはや展開を行うクォートのような演算子ではなくなってしまったので
構築子の名前はqr
から変更されたのです。
rx
は Ȳule expression" を意味するか
あるいは Ȳegex" の省略形です :-)
As the syntax indicates, it is now more closely analogous to a sub {...}
constructor. In fact, that analogy will run very deep in Perl 6.
構文が示すように、よりsub {...}
コンストラクターに類似のものとなりました。
事実、そのような類推はPerl 6のおいて非常に深く入り込んだものとなるでしょう。
Just as a raw {...}
is now always a closure (which may still
execute immediately in certain contexts and be passed as a reference
in others), so too a raw /.../
is now always a rule (which may still
match immediately in certain contexts and be passed as a reference
in others).
生の{...}
は常にクロージャとなります
(それでも幾つかのコンテキストでは即座に実行される可能性がありますし、
別のもののリファレンスとして渡される可能性もあります)。
同様に、生の/.../
は常にルールとなります
(それでも幾つかのコンテキストでは即座にマッチが行われますし、
他のもののリファレンスとして渡される可能性もあります)。
Specifically, a /.../
matches immediately in a value context (void,
Boolean, string, or numeric), or when it is an explicit argument of
a ~~
. Otherwise it's a rule constructor. So this:
特に、/.../
は void、boolean、string、numericなどのコンテキストで
即座にマッチが行われます。
あるいは陽に~~
の引数であるときににマッチが行われます。
そうでなければ、それはルールコンストラクタです。ですから:
$var = /pattern/;
no longer does the match and sets $var
to the result.
Instead it assigns a rule reference to $var
.
この例ではもはやマッチは行われず、$var
にマッチの結果が格納されることもありません。
その代わりに、$var
にはルールのリファレンスが代入されます。
The two cases can always be distinguished using m{...}
or rx{...}
:
m{...}
か rx{...}
を使ったときには常に区別することができます:
$var = m{pattern}; # 即座にルールのマッチングを行い、結果を代入する $var = rx{pattern}; # ルール式自身を代入する
Note that this means that former magically lazy usages like:
次のような、マジカルな遅延の使用は 常に通常のセマンティクスでの結果となります:
@list = split /pattern/, $str;
are now just consequences of the normal semantics.
It's now also possible to set up a user-defined subroutine that acts
like grep
:
grep
のように動作するユーザー定義のサブルーチンを
作り出すことができるようになりました:
sub my_grep($selector, *@list) { given $selector { when Rule { ... } when Code { ... } when Hash { ... } # etc. } }
Using {...}
or /.../
in the scalar context of the first argument
causes it to produce a Code
or Rule
reference, which the switch
statement then selects upon.
第一引数のスカラーコンテキストにおける {...}
か /.../
は
Code
のリファレンスもしくは Rule
のリファレンスを生成します。
これはswitch文が選択するときに使うものです。
Backtracking over a single colon causes the rule engine not to retry the preceding atom:
一つのコロンをまたいだバックトラッキングはルールエンジンに、 先行するアトムに対してリトライを行わないことを強制します:
m:w/ \( <expr> [ , <expr> ]* : \) /
(i.e. there's no point trying fewer <expr>
matches, if there's
no closing parenthesis on the horizon)
(つまり、閉じ括弧がない場合には <expr>
をより少ない数で試すということはしないということです)
Backtracking over a double colon causes the surrounding group of alternations to immediately fail:
ダブルコロンをまたいだバックトラッキングは それを含むグループの選択肢を即座に失敗させます:
m:w/ [ if :: <expr> <block> | for :: <list> <block> | loop :: <loop_controls>? <block> ] /
(i.e. there's no point trying to match a different keyword if one was already found but failed).
(つまり、もし一つのキーワードが見つかってそれが失敗したならば 他のキーワードを試すことはしないということです)
Backtracking over a triple colon causes the current rule to fail outright (no matter where in the rule it occurs):
トリプルコロンをまたいだバックトラッキングは それを囲むルールを失敗させます (ルールのどこであるかは意味がありません):
rule ident { ( [<alpha>|_] \w* ) ::: { fail if %reserved{$0} } | " [<alpha>|_] \w* " }
m:w/ get <ident>? /
(i.e. using an unquoted reserved word as an identifier is not permitted)
(予約語をクォートで囲まずに識別子として使うことは許されません)
Backtracking over a <commit>
assertion causes the entire match
to fail outright, no matter how many subrules down it happens:
表明 <commit>
をまたいだバックトラッキングはマッチ全体を即座に失敗させます。
どのくらいのサブルールがあったかには依存しません:
rule subname { ([<alpha>|_] \w*) <commit> { fail if %reserved{$0} } } m:w/ sub <subname>? <block> /
(i.e. using a reserved word as a subroutine name is instantly fatal to the ȳurrounding" match as well)
(予約語をサブルーチン名として使うことは“それを囲んでいる” マッチを失敗させるということです)
A <cut>
assertion always matches successfully, and has the
side effect of deleting the parts of the string already matched.
表明 <cut>
は常に成功します。
副作用として文字列のすでにマッチした部分を切り取ります。
Attempting to backtrack past a <cut>
causes the complete match
to fail (like backtracking past a <commit>
. This is because there's
now no preceding text to backtrack into.
<cut>
よりも前にバックトラックしようとすることは、
マッチを失敗させます (<commit>
に対するバックトラックと同様)。
これは後戻りすべきテキストがもはや存在しないからです。
This is useful for throwing away successfully processed input when matching from an input stream or an iterator of arbitrary length.
これは入力ストリームや任意の長さのイテレータに対して マッチングを行うときに成功した部分を返すのに便利です。
The analogy between sub
and rule
extends much further.
sub
とrule
の類似性はさらに拡大されます。
Just as you can have anonymous subs and named subs...
無名サブルーチンと名前付きサブルーチンのように…
...so too you can have anonymous rules and named rules:
そう、無名のルールと名前のついたルールを持つことができるんです:
rule ident { [<alpha>|_] \w* }
# and later...
@ids = grep /<ident>/, @strings;
As the above example indicates, it's possible to refer to named rules, such as:
先の例が示すように、以下のように名前付きルールを 別の名前付き表明の中で参照することができます
rule serial_number { <[A..Z]> \d**{8} } rule type { alpha | beta | production | deprecated | legacy }
in other rules as named assertions:
rule identification { [soft|hard]ware <type> <serial_number> }
The null pattern is now illegal.
空パターンは不正なものとなりました・
To match whatever the prior successful rule matched, use:
直前に成功したマッチしたものにマッチさせるには以下のようにします:
/<prior>/
To match the zero-width string, use:
幅がない文字列にマッチさせるには次のようにします:
/<null>/
For example:
たとえば:
split /<?null>/, $string
splits between characters.
これはキャラクタごとの分割を行います。
To match a null alternative, use:
空の選択肢をマッチさせるには以下のようにします:
/a|b|c|<?null>/
This makes it easier to catch errors like this:
これは以下のようにエラーを補足するのを簡単にします:
m:w/ [ | if :: <expr> <block> | for :: <list> <block> | loop :: <loop_controls>? <block> ] /
However, it's okay for a non-null syntactic construct to have a degenerate case matching the null string:
しかし、空でない構文的な構造を空文字列にマッチングするような degenerateなケースに使うこともできます:
$something = ""; /a|b|c|$something/;
A match always returns a ȭatch objectɬ which is also available
as $/
, which is an environmental lexical declared in the outer
subroutine that is calling the rule. (A closure lexically embedded
in a rule does not redeclare $/
, so $/
always refers to the
current match, not any prior submatch done within the closure).
マッチは常に$/
として参照することができ、
呼び出したルールの外側のサブルーチンの中でレキシカルに宣言された
変数である
“マッチオブジェクト”を返します
(クロージャは$/
を再宣言していないルールに
レキシカルに埋め込まれています。ですから、$/
は常に
カレントのマッチを参照していて、クロージャの中にある先行する
なんらかのサブマッチを参照することはありません)。
Notionally, a match object contains (among other things) a boolean success value, a scalar Ȳesult objectɬ an array of ordered submatch objects, and a hash of named submatch objects. To provide convenient access to these various values, the match object evaluates differently in different contexts:
マッチオブジェクトは概念としては 成功した値を表す論理値、“結果オブジェクト”であるスカラー、 順番に並んだサブマッチの配列、名前付けされたサブマッチオブジェクトのハッシュ などから構成されます。 これらの様々な値に対するアクセスに便宜を図るために、 マッチオブジェクトは異なるコンテキストでは異なる評価がなされます:
In boolean context it evaluates as true or false (i.e. did the match succeed?):
ブールコンテキスト(boolean context)においては真/偽として 評価されます(つまりマッチが成功したか?):
if /pattern/ {...} # or: /pattern/; if $/ {...}
In string context it evaluates to the stringified value of its result object, which is usually the entire matched string:
文字列コンテキストにおいては 結果オブジェクトの値を文字列化したものとして評価されます。 これは通常マッチした部分全体です:
print %hash{ "{$text ~~ /<?ident>/}" }; # or equivalently: $text ~~ /<?ident>/ && print %hash{~$/};
But generally you should say ~$/
if you mean ~$/
.
しかし一般的には~$/
を目的としていたのなら
~$/
と書くべきでしょう。
In numeric context it evaluates to the numeric value of its result object, which is usually the entire matched string:
数値コンテキストにおいては、 結果オブジェクトの数値としての値が評価されます。 これは通常マッチした部分全体です。
$sum += /\d+/; # or equivalently: /\d+/; $sum = $sum + $/;
When called as a closure, a Match object evaluates to its underlying
result object. Usually this is just the entire match string, but
you can override that by calling return
inside a rule:
クロージャとして呼び出されたとき、マッチオブジェクトはその下にある
結果オブジェクトのために評価されます。
通常これはマッチした文字列全体ですが、ルールの中で
return
を呼び出すことによってオーバーライドすることができます:
my $moose = m:{ <antler> <body> { return Moose.new( body => $<body>().attach($<antler>()) ) } # match succeeds -- ignore the rest of the rule }.();
$()
is a shorthand for $/.()
or $/()
. The result object
may be of any type, not just a string.
$()
は$/.()
や$/()
の短縮表記です。
その結果オブジェクトは文字列に限らず任意の型である可能性があります
You may also capture a subset of the match as the result object using
the <(...)>
construct:
マッチのサブセットを<(...)>
構造を使った結果オブジェクトであるかのように
キャプチャすることができます:
"foo123bar" ~~ / foo <( \d+ )> bar / say $(); # says 123
In this case the result object is always a string when doing string matching, and a list of one or more elements when doing array matching.
この場合結果オブジェクトは 文字列マッチングが行われたときには常に文字列であり、 配列マッチングが行われたときには常に一つ以上の要素を持つリストです。
When used as an array, a Match object pretends to be an array of all its positional captures. Hence
配列として使ったとき、マッチオブジェクトは すべてのpositional キャプチャの配列として扱われます。 したがって
($key, $val) = m:w/ (\S+) => (\S+)/;
can also be written:
これは次のように書くことができます:
$result = m:w/ (\S+) => (\S+)/; ($key, $val) = @$result;
To get a single capture into a string, use a subscript:
一つのキャプチャを文字列として取得するには添え字を使います:
$mystring = "{ m:w/ (\S+) => (\S+)/[0] }";
To get all the captures into a string, use a Ⱥen" slice:
すべてのキャプチャを文字列として取得するには、“zen”スライスを使います:
$mystring = "{ m:w/ (\S+) => (\S+)/[] }";
Note that, as a scalar variable, $/
doesn't automatically flatten
in list context. Use @$/
or $/[]
to flatten as an array.
スカラー変数としては、$/
はリストコンテキストのときに
自動的に平滑化(flatten)されることはないということに注意してください。
配列として平滑化するには@$/
か$/[]
を使います。
When used as a hash, a Match object pretends to be a hash of all its named
captures. The keys do not include any sigils, so if you capture to
variable @<foo>
its real name is $/{'foo'}
or $/<foo>
.
However, you may still refer to it as @<foo>
anywhere $/
is visible. (But it is erroneous to use the same name for two different
capture datatypes.)
ハッシュとして使用したとき、マッチオブジェクトはすべての名前付きキャプチャ
のハッシュであるように扱われます。
そのキーにはsigilsは含まれることはないので、
変数 @<foo>
にキャプチャした場合の本当の名前は
@<foo>
もしくは $/<foo>
となります。
しかしながら、$/
が見えるところであれば
@<foo>
として参照することも可能です
(しかし二つの異なるキャプチャデータ型を同じ名前で参照するために
使うのは間違いです)。
Note that, as a scalar variable, $/
doesn't automatically flatten
in list context. Use %$/
or $/{}
to flatten as a hash, or bind
it to a variable of the appropriate type.
$/
はリストコンテキストに置かれたときに
スカラー変数として自動的に平滑化されることはないということに注意してください。
ハッシュを平滑化するには%$/
か$/{}
を使うか、
適切な型を持つ変数に対して束縛するかします。
The numbered captures may be treated as named, so $<0 1 2>
is equivalent to $/[0,1,2]
. This allows you to write slices of
intermixed named and numbered captures.
番号付けによりキャプチャされたものは名前付きキャプチャとして
扱うことができるので、$<0 1 2>
は$/[0,1,2]
と等価です。
これは名前によるキャプチャと番号によるキャプチャを混ぜた
スライスを記述することを許可します。
In ordinary code, variables $0
, $1
, etc. are just aliases into
$/[0]
, $/[1]
, etc. Hence they will all be undefined if the
last match failed (unless they were explicitly bound in a closure without
using the let
keyword).
通常のコードでは、$0
、$1
、... といった変数は
$/[0]
、$/[1]
、... の単なる別名です。
したがって、最後に行われたマッチが失敗したならば
(let
キーワードを使わないクロージャの中で陽に束縛していない限り)、
これらはすべて未定義値となります。
Match
objects have methods that provide additional information about
the match. For example:
Match
オブジェクトはそのマッチに関する付加的な情報を提供するための
メソッドを持っています。
例を挙げましょう:
if m/ def <ident> <codeblock> / { say "Found sub def from index $/.from() to index $/.to()"; }
All match attempts--successful or not--against any rule, subrule, or
subpattern (see below) return an object of class Match
. That is:
任意のルール、サブルール、サブパターン(後述)に対して行われたすべてのマッチは、
それが成功したか失敗したかによらず、Match
クラスのオブジェクトを
返します。
つまり:
$match_obj = $str ~~ /pattern/; say "Matched" if $match_obj;
This returned object is also automatically assigned to the lexical
$/
variable, unless the match statement is inside another rule. That is:
この返却されたオブジェクトは、
マッチを行った文が他のルールの内側にあるものでない限り
自動的にレキシカル変数$/
に代入されます:
$str ~~ /pattern/; say "Matched" if $/;
Inside a rule, the $/
variable holds the current rule's
incomplete Match
object (which can be modified via the internal $/
.
For example:
あるルールの内側では、$/
変数はカレントのルールの
不完全なMatch
オブジェクトを保持します
(このオブジェクトは内部的な$/
を通して変更を加えることができます)。
例を挙げましょう:
$str ~~ / foo # 'foo' にマッチ { $/ = 'bar' } # しかし 'bar' にマッチしたかのようにする /; say $/; # 'bar' を出力する
This is slightly dangerous, insofar as you might return something that
does not behave like a Match
object to some context that requires
one. Fortunately, you normally just want to return a result object instead:
これは明らかに危険なものです。
要求されたものではない何らかのコンテキストに対する
Match
オブジェクトのように振舞わない何かを返してしまうかもしれません。
幸運にも、通常は結果オブジェクトを代わりに返すことで済みます:
$str ~~ / foo # 'foo' にマッチ { return 'bar' } # しかし 'bar' にマッチしたかのようにする /; say $(); # 'bar' を出力する
Any part of a rule that is enclosed in capturing parentheses is called a subpattern. For example:
ルールの中でキャプチャを行う括弧によって囲まれている部分は サブパターン(subpattern)と呼ばれる。 例を挙げましょう:
# subpattern # _________________/\____________________ # | | # | subpattern subpattern | # | __/\__ __/\__ | # | | | | | | m:w/ (I am the (walrus), ( khoo )**{2} kachoo) /;
Each subpattern in a rule produces a Match
object if it is
successfully matched.
ルールの中にあるそれぞれのサブパターンは、それがマッチに成功
しているならばMatch
オブジェクトを生成します。
Each subpattern's Match
object is pushed onto the array inside
the outer Match
object belonging to the surrounding scope (known as
its parent Match
object). The surrounding scope may be either the
innermost surrounding subpattern (if the subpattern is nested) or else
the entire rule itself.
各サブパターンのMatch
オブジェクトは
それを囲むスコープに属していて外側にあるMatch
オブジェクト
(親Match
オブジェクトとして知られています)
の中にある配列にプッシュされます。
サブパターンを囲むスコープは、サブパターンがネストしていたときの
(そのサブパターンを囲んでいる中で)最も内側のものか、
ルール全体そのものかのいずれかです。
Like all captures, these assignments to the array are hypothetical, and are undone if the subpattern is backtracked.
すべてのキャプチャと同様に、配列に対する代入はhypotheticalであり、 サブパターンがバックトラックした場合には巻き戻されます。
For example, if the following pattern matched successfully:
たとえば、以下のようなパターンマッチが成功したとしましょう:
# subpat-A # _________________/\____________________ # | | # | subpat-B subpat-C | # | __/\__ __/\__ | # | | | | | | m:w/ (I am the (walrus), ( khoo )**{2} kachoo) /;
then the Match
objects representing the matches made by subpat-B
and subpat-C would be successively pushed onto the array inside subpat-
A's Match
object. Then subpat-A's Match
object would itself be
pushed onto the array inside the Match
object for the entire rule
(i.e. onto $/
's array).
このとき、Match
オブジェクトはsubpat-Bとsubpat-Cによって生成され
subpat-AのMatch
オブジェクトの中にある配列にプッシュされた
マッチを表します。
As a result of these semantics, capturing parentheses in Perl 6 are hierarchical, not linear (see Nested subpattern captures).
これらのセマンティクスにより、Perl 6におけるキャプチャを行う括弧は 線形(linear)なものではなく階層的(hierarchical)なものです (Nested subpattern capturesを参照)。
The array elements of a Match
object are referred to using either the
standard array access notation (e.g. $/[0]
, $/[1]
, $/[2]
, etc.)
or else via the corresponding lexically scoped numeric aliases (i.e.
$0
, $1
, $2
, etc.) So:
Match
オブジェクトの配列要素は
標準の配列アクセス表記($/[0]
、$/[1]
、$/[2]
、...)か
レキシカルスコープの数値エイリアス($0
、$1
、$2
、...)の
いずれかを使って参照されます。
したがって:
say "$/[1] was found between $/[0] and $/[2]";
is the same as:
これは以下のものと同じです:
say "$1 was found between $0 and $2";
Note that, in Perl 6, the numeric capture variables start from $0, not
$1, with the numbers corresponding to the element's index inside $/
.
Perl 6では、数値捕獲変数は$1からではなく$0から始まっていて
$/
の中の要素のに対する添え字に対応しているということに注意してください。
The array elements of the rule's Match
object (i.e. $/
)
store individual Match
objects representing the substrings that where
matched and captured by the first, second, third, etc. outermost
(i.e. unnested) subpatterns. So these elements can be treated like fully
fledged match results. For example:
ルールのMatch
オブジェクト($/
)の配列要素は
最初、二番目、三番目、...の
最も外側(outermost、ネストしていない)にあるサブパターンによって
マッチしキャプチャされた部分文字列を
表している独立したMatch
オブジェクトを格納したものです。
ですから、これらの要素はマッチの結果として扱うことができます。
例を挙げましょう:
if m/ (\d\d\d\d)-(\d\d)-(\d\d) (BCE?|AD|CE)?/ { ($yr, $mon, $day) = $/[0..2] $era = "$3" if $3; # stringify/boolify @datepos = ( $0.from() .. $2.to() ); # Call Match methods }
Substrings matched by nested subpatterns (i.e. nested capturing
parens) are assigned to the array inside the subpattern's parent Match
surrounding subpattern, not to the array of $/
.
ネストしたサブパターン(つまりネストしたキャプチャ用括弧)により
マッチした部分文字列はそのサブパターンが属する親のMatch
の
内部にある配列に代入され、$/
の配列に対しては行われなません。
This behaviour is quite different to Perl 5 semantics:
この振る舞いはPerl 5におけるセマンティクスと大きく異なります:
# Perl 5 の場合 # # $1--------------------- $4--------- $5------------------ # | $2--------------- | | | | $6---- $7------ | # | | $3-- | | | | | | | | | | # | | | | | | | | | | | | | | m/ ( A (guy|gal|g(\S+) ) ) (sees|calls) ( (the|a) (gal|guy) ) /x;
In Perl 6, nested parens produce properly nested captures:
Perl 6では、ネストした括弧対は適切にネストしたキャプチャを生成します:
# Perl 6 の場合 # # $0--------------------- $1--------- $2------------------ # | $0[0]------------ | | | | $2[0]- $2[1]--- | # | | $0[0][0] | | | | | | | | | | # | | | | | | | | | | | | | | m/ ( A (guy|gal|g(\S+) ) ) (sees|calls) ( (the|a) (gal|guy) ) /;
If a subpattern is directly quantified (using any quantifier), it no
longer produces a single Match
object. Instead, it produces a list
of Match
objects corresponding to the sequence of individual matches
made by the repeated subpattern.
あるサブパターンが(何らかの量指定子を使って)直接数量化を行ったならば、
それはもはや(それに対応する)単一のMatch
オブジェクトを作ることはありません。
代わりに、
繰り返されたサブパターンにより生成されたここの独立したマッチの並びを
表すようなMatch
オブジェクトのリストを生成します。
Because a quantified subpattern returns a list of Match
objects, the
corresponding array element for the quantified capture will store a
reference to a (nested) array, rather than a single Match
object.
For example:
数量化されたサブパターンはMatch
オブジェクトを返すので、
数量化されたキャプチャのための配列の要素は
単一のMatch
オブジェクトではなく
(ネストした)配列に対するリファレンスを格納するでしょう。
例を挙げます:
if m/ (\w+) \: (\w+ \s+)* / { say "Key: $0"; # Unquantified --> single Match say "Values: { @{$1} }"; # Quantified --> array of Match }
A subpattern may sometimes be nested inside a quantified non-capturing structure:
サブパターンは数量化されたキャプチャを行わない構造の内側で ネストすることがあるかもしれません。
# non-capturing quantifier # __________/\____________ __/\__ # | || | # | $0 $1 || | # | _^_ ___^___ || | # | | | | | || | m/ [ (\w+) \: (\w+ \h*)* \n ]**{2...} /
Non-capturing brackets don't create a separate nested lexical scope,
so the two subpatterns inside them are actually still in the rule's
top-level scope. Hence their top-level designations: $0
and $1
.
キャプチャを行わないブラケットは
分割されたネストするレキシカルスコープを生成することはありません。
ですから、そういったものの中にある二つのサブパターンは
依然としてルールの中のトップレベルのスコープです。
したがって、それらのトップレベルdesignationsは $0
と$1
なのです。
However, because the two subpatterns are inside a quantified
structure, $0
and $1
will each contain a reference to an array.
The elements of that array will be the submatches returned by the
corresponding subpattern on each iteration of the non-capturing
parentheses. For example:
しかしながら、二つのサブパターンは数量化された構造の中にあるので、
$0
と$1
はそれぞれ配列に対するリファレンスを保持することになるでしょう。
そのような配列の要素はキャプチャを行わない括弧対のそれぞれの繰り返しにおいて
対応したサブパターンによって返されたサブマッチになります。
my $text = "foo:food fool\nbar:bard barb";
# $0-- $1------ # | | | | $text ~~ m/ [ (\w+) \: (\w+ \h*)* \n ]**{2...} /;
# Because they're in a quantified non-capturing block... # $0 contains the equivalent of: # これらの捕獲集合はキャプチャを行わないブロックの中にあるので # $0 の内容は以下のようなものになります: # # [ Match.new(str=>'foo'), Match.new(str=>'bar') ] # # and $1 contains the equivalent of: # そして $1 はこう: # # [ Match.new(str=>'food '), # Match.new(str=>'fool' ), # Match.new(str=>'bard '), # Match.new(str=>'barb' ), # ]
In contrast, if the outer quantified structure is a capturing
structure (i.e. a subpattern) then it will introduce a nested
lexical scope. That outer quantified structure will then
return an array of Match
objects representing the captures
of the inner parens for every iteration (as described above). That is:
対照的に、外側の数量化された構造がキャプチャを行う構造(つまりサブパターン)で
あれば、それはネストしたレキシカルスコープを持ち込みます。
そのような外側の数量化された構造は、
その内側にあるすべての繰り返しに対して括弧対により捕獲された
ものを表すMatch
オブジェクトの配列を返すでしょう。
つまりこういうことです:
my $text = "foo:food fool\nbar:bard barb";
# $0----------------------- # | | # | $0[0] $0[1]--- | # | | | | | | $text ~~ m/ ( (\w+) \: (\w+ \h*)* \n )**{2...} /;
# Because it's in a quantified capturing block, # $0 contains the equivalent of: # 数量化されたキャプチャのためのブロックの内側にあるので # $0 の内容は以下のようになります: # # [ Match.new( str=>"foo:food fool\n", # arr=>[ Match.new(str=>'foo'), # [ # Match.new(str=>'food '), # Match.new(str=>'fool'), # ] # ], # ), # Match.new( str=>'bar:bard barb', # arr=>[ Match.new(str=>'bar'), # [ # Match.new(str=>'bard '), # Match.new(str=>'barb'), # ] # ], # ), # ] # # and there is no $1 # そしてこの場合 $1はありません
In other words, quantified non-capturing parens collect their components into handy flattened lists, whereas quantified capturing parens collect their components in a handy hierarchical structure.
言い換えれば、数量化されたキャプチャを行わない括弧対は それらにマッチした内容を平滑化されたリストに集め、 数量化されたキャプチャを行う括弧対は それらにマッチした内容を階層的な構造に集めるということです。
The index of a given subpattern can always be statically determined, but is not necessarily unique nor always monotonic. The numbering of subpatterns restarts in each lexical scope (either a rule, a subpattern, or the branch of an alternation).
与えられたサブパターンの添え字は常に静的に決定することができますが、 一意である必要も常に単調である必要もありません。 サブパターンの番号付けはレキシカルスコープが始まるたびごと (ルール、サブパターン、もしくは選択の分岐) にリスタートします。
In particular, the index of capturing parentheses restarts after each
|
. Hence:
とくに、キャプチャのための括弧対の番号は|
の後でリスタートされます。
したがって:
# $0 $1 $2 $3 $4 $5 $tune_up = rx/ (don't) (ray) (me) (for) (solar tea), (d'oh!) # $0 $1 $2 $3 $4 | (every) (green) (BEM) (devours) (faces) /;
This means that if the second alternation matches, the @$/
array will
contain ('every', 'green', 'BEM', 'devours', 'faces')
, rather than
(undef, undef, undef, undef, undef, undef, 'every', 'green', 'BEM',
'devours', 'faces')
(as the same regex would in Perl 5).
これは二番目の選択においてマッチが成功したならば<@$/>という配列は
(Perl 5における同様の正規表現においてそうであるような)
(undef, undef, undef, undef, undef, undef, 'every', 'green', 'BEM',
'devours', 'faces')
という内容ではなく、
('every', 'green', 'BEM', 'devours', 'faces')
になるということです。
Note that it is still possible to mimic the monotonic Perl 5 capture indexing semantics. See Numbered scalar aliasing below for details.
それでもPerl 5における単調な添え字付けを模倣することも可能です。 詳しくはこの後にあるNumbered scalar aliasingを参照してください。
Any call to a named <rule>
within a pattern is known as a subrule.
あるパターンにおいてなんらかの名前のついた<rule>
を呼び出すことは
サブルールとして知られています。
Any bracketed construct that is aliased (see the aliasing manpage below) to a named variable is also a subrule.
ブラケット対による構造は名前つき変数に対する別名付け(後述のthe aliasing manpageを参照) であると同時にサブルールでもあります。
For example, this rule contains three subrules:
たとえば以下のようなルールは三つのサブルールからなります:
# subrule subrule subrule # __^__ _______^______ __^__ # | | | | | | m/ <ident> $<spaces>:=(\s*) <digit>+ /
Just like subpatterns, each successfully matched subrule within a rule
produces a Match
object. But, unlike subpatterns, that Match
object is not assigned to the array inside its parent Match
object.
Instead, it is assigned to an entry of the hash inside its parent Match
object. For example:
サブパターンと同様に、ルールの中にあるマッチに成功したサブルールは
Match
オブジェクトを生成します。
しかし、サブパターンと異なり、生成されたMatch
オブジェクトは
親のMatch
オブジェクトに属する配列に代入されることはありません。
代わりに、親のMatch
オブジェクトに属するハッシュのエントリに代入されます。
例を挙げましょう:
# .... $/ ..................................... # : : # : .... $/[0] .................. : # : : : : # : $/<ident> : $/[0]<ident> : : # : __^__ : __^__ : : # : | | : | | : : m:w/ <ident> \: ( known as <ident> previously ) /
The hash entries of a Match
object can be referred to using any of the
standard hash access notations ($/{'foo'}
, $/<bar>
, $/ォbazサ
,
etc.), or else via corresponding lexically scoped aliases ($<foo>
,
$ォbarサ
, $<baz>
, etc.) So the previous example also implies:
Match
オブジェクトのハッシュエントリは通常のハッシュに対する
アクセス表記のいずれを使っても
($/{'foo'}
, $/<bar>
, $/ォbazサ
, etc.)
アクセスすることができます。
あるいは、適切なレキシカルスコープの別名
($<foo>
, $ォbarサ
, $<baz>
, etc.)
でアクセスすることも可能です。
ですから先に挙げた例を使うと以下のようになります:
# $<ident> $0<ident> # __^__ __^__ # | | | | m:w/ <ident> \: ( known as <ident> previously ) /
Note that it makes no difference whether a subrule is angle-bracketted (<
<ident
>>) or aliased ($<ident> := (<alpha>\w*)
. The name's the thing.
サブルールがアングルブラケット対によって指定されている
(<ident>
)
のと別名によって指定されている
($<ident> := (<alpha>\w*)
)
のとの違いには意味がないことに注意してください。
名前が重要なのです。
If a subrule appears two (or more) times in any branch of a lexical
scope (i.e. twice within the same subpattern and alternation), or if the
subrule is quantified anywhere within a given scope, then its
corresponding hash entry is always assigned a reference to an array of
Match
objects, rather than a single Match
object.
あるサブルールが二回以上レキシカルスコープの中の分岐のいずれかで出現した場合
(同じサブパターンと選択の中で複数回ということ)、
もしくはそのサブルールが与えられたスコープの中のどこかで数量化されていた場合、
そのサブルールに対応するハッシュのエントリには
単一のMatch
オブジェクトではなくMatch
オブジェクトの配列に対する
リファレンスが常に代入されます。
Successive matches of the same subrule (whether from separate calls, or
from a single quantified repetition) append their individual Match
objects to this array. For example:
同じルールが後続しているマッチ(別の呼び出しであるか
単一の数量化の繰り返しのいずれか)では
上記の配列に対して(サブルールに対応する)独立したMatch
オブジェクトが
追加されます。
例を挙げましょう:
if m:w/ mv <file> <file> / { $from = $<file>[0]; $to = $<file>[1]; }
Likewise, with a quantified subrule:
同様に、数量化されたサブルールの場合:
if m:w/ mv <file>**{2} / { $from = $<file>[0]; $to = $<file>[1]; }
Likewise, with a mixture of both:
両者を混在させた場合:
if m:w/ mv <file>+ <file> / { $to = pop @{$<file>}; @from = @{$<file>}; }
However, if a subrule is explicitly renamed (or aliased -- see the aliasing manpage), then only the "final" name counts when deciding whether it is or isn't repeated. For example:
しかしながら、あるサブルールが陽に名前がついたもの(もしくは別名付けされたもの -- the aliasing manpageを参照)であった場合には、 それが繰り返されたものであるかそうでないかが決定されるときの “最後の”名前だけが採用されます。 例を挙げましょう:
if m:w/ mv <file> $<dir>:=<file> / { $from = $<file>; # Only one subrule named <file>, so scalar # <file>という名前のサブルールはただ一つなのでスカラー $to = $<dir>; # The Capture Formerly Known As <file> # この捕獲は形式的には<file>である }
Likewise, neither of the following constructions causes <file>
to
produce an array of Match
objects, since none of them has two or more
<file>
subrules in the same lexical scope:
同様に、
同じレキシカルスコープ中に
二つ以上の<file>
サブルールを持つものがないときにも、
後続する構造が <file>
に対して
Match
オブジェクトの配列の生成を行わせることはありません:
if m:w/ (keep) <file> | (toss) <file> / { # Each <file> is in a separate alternation, therefore <file> # is not repeated in any one scope, hence $<file> is # not an array ref... # それぞれの <file> は別々の選択肢にあるので # <file> は一つのスコープの中で繰り返されてはいない。このため # $<file>は配列のリファレンスにはならない… $action = $0; $target = $<file>; }
if m:w/ <file> \: (<file>|none) / { # Second <file> nested in subpattern which confers a # different scope... # 二番目の <file> は異なるスコープに属するサブパターンにある $actual = $/<file>; $virtual = $/[0]<file> if $/[0]<file>; }
On the other hand, unaliased square brackets don't confer a separate
scope (because they don't have an associated Match
object). So:
その一方で、
別名付けされていない角括弧対は別のスコープを与えることはありません
(なぜなら角括弧対は対応付けられたMatch
オブジェクトを持っていないからです)。
ですから、
if m:w/ <file> \: [<file>|none] / { # Two <file>s in same scope # 二つの <file> は同じスコープの中にある $actual = $/<file>[0]; $virtual = $/<file>[1] if $/<file>[1]; }
Aliases can be named or numbered. They can be scalar-, array-, or hash-like. And they can be applied to either capturing or non-capturing constructs. The following sections highlight special features of the semantics of some of those combinations.
別名は名前によっても番号によってもできます。 別名はスカラーでも、配列でも、はたまたハッシュのようにもできます。 そして別名は捕獲を行う構造に対してもできますし、 捕獲を行わない構造に対してもできます。 後続のセクションではこれらの組み合わせのいくつかの特別な機能を紹介します。
If a named scalar alias is applied to a set of capturing parens:
名前つきスカラーを使った別名が捕獲を行う括弧対の集合に対するものであった場合:
# ______/capturing parens\_____ # | | # | | m:w/ $<key>:=( (<[A..E]>) (\d**{3..6}) (X?) ) /;
then the outer capturing parens no longer capture into the array of
$/
(like unaliased parens would). Instead the aliased parens capture
into the hash of $/
; specifically into the hash element
whose key is the alias name.
外側にある捕獲を行う括弧対はもはや$/
に属する配列に対して捕獲を格納することは
ありません。その代わりに、別名がつけられた括弧対による捕獲は
$/
に属し、
キーとして別名の名前を使うハッシュに対して格納されます。
So, in the above example, a successful match sets
$<key>
(i.e. $/<key>
), but not $0
(i.e. not $/[0]
).
ですから、先の例では成功したマッチは
$0
(または$/[0]
)ではなく、
$<key>
($/<key>
)に格納されます。
More specifically:
より詳しく説明すると:
$/<key>
will contain the Match
object that would previously have
been placed in $/[0]
.
$/<key>
は
かつて$/[0]
であったようなMatch
オブジェクトを保持します。
$/<key>[0]
will contain the A-E letter,
$/<key>[0]
には A-E の文字から構成されます。
$/<key>[1]
will contain the digits,
$/<kye>[1]
には数字列が入ります。
$/<key>[2]
will contain the optional X.
$/<key>[2]
には省略することもできる X が入ります。
Another way to think about this behaviour is that aliased parens create a kind of lexically scoped named subrule; that the contents of the brackets are treated as if they were part of a separate subrule whose name is the alias.
この振る舞いに関する別の考え方は、 これが別名がつけられた括弧対がレキシカルなスコープを持った 名前つきサブルールのようなものを生成するというものです。 そのようなブラケット対の構造はその名前が別名としてつけられたもので あるかのような毒利したサブルールの一部であるかのように扱われます。
If an named scalar alias is applied to a set of non-capturing brackets:
名前つきスカラーが 捕獲を行わないブラケット対の集合に対して適用された場合:
# ___/non-capturing brackets\__ # | | # | | m:w/ $<key>:=[ (<[A..E]>) (\d**{3..6}) (X?) ] /;
then the corresponding $/<key>
object contains only the string
matched by the non-capturing brackets.
対応する$/<key>
オブジェクトは
捕獲を行わないブラケット対にマッチした文字列のみを
保持します。
In particular, the array of the $/<key>
entry is empty. That's
because square brackets do not create a nested lexical scope, so the
subpatterns are unnested and hence correspond to $0, $1, and $2, and
not to $/<key>[0]
, $/<key>[1]
, and $/<key>[2]
.
このとき、$/<key>
の配列エントリは空です。
これは、ブラケット対はネストしたレキシカルスコープを作り出すことはないので
サブパターンはネストしていないためです。
したがってそれらは$0、$1、$2に対応し、
$/<key>[0]
, $/<key>[1]
, and $/<key>[2]
では
ありません。
In other words:
言い換えると
$/<key>
will contain the complete substring matched by the square
brackets (in a Match
object, as described above),
$/<key>
は
(先に説明した通りMatch
オブジェクトの中で)
ブラケット対にマッチした部分文字列全体を保持します。
そして、
$0
will contain the A-E letter,
$0
は A-E の文字を保持します。
$1
will contain the digits,
$1
は数字列を保持します。
$2
will contain the optional X.
$2
は省略可能な Xを保持します。
If a subrule is aliased, it assigns its Match
object to the hash
entry whose key is the name of the alias. And it no longer assigns
anything to the hash entry whose key is the subrule name. That is:
サブルールに別名がつけられていた場合、そのサブルールは自身を表す
Match
オブジェクトを
キーとして別名を使う
ハッシュエントリに代入します。
そして、サブルールの名前をキーとするハッシュエントリに
代入することはありません。
つまりこういうことです:
if m:/ ID\: $<id>:=<ident> / { say "Identified as $/<id>"; # $/<ident> は未定義 }
Hence aliasing a subrule changes the destination of the subrule's Match
object. This is particularly useful for differentiating two or more calls to
the same subrule in the same scope. For example:
したがってサブルールに別名をつけることはそのサブルールのMatch
オブジェクトの
代入先を変更することです。
これは同じスコープにおいて同じ名前のサブルールの呼び出しを複数回行ったときに
それらを区別するのに便利でしょう。
例を挙げます:
if m:w/ mv <file>+ $<dir>:=<file> / { @from = @{$<file>}; $to = $<dir>; }
If a numbered alias is used instead of a named alias:
名前による別名付けではなく番号による別名付けが行われた場合:
m/ $1:=(<-[:]>*) \: $0:=<ident> /
the behaviour is exactly the same as for a named alias (i.e the various
cases described above), except that the resulting Match
object is
assigned to the corresponding element of the appropriate array, rather
than to an element of the hash.
その振る舞いは名前による別名付けとまったく同じです
(先に説明した様々なケースにおいて)。
ただし、結果を格納しているMatch
オブジェクトが
ハッシュの要素にではなく
適切な配列の該当する要素に代入されるという点が異なります。
If any numbered alias is used, the numbering of subsequent unaliased subpatterns in the same scope automatically increments from that alias number (much like enum values increment from the last explicit value). That is:
もしなんらかの番号による別名付けが行われたならば、 同じスコープに属するそれに後続する番号指定のないサブパターンは 自動的に別名に使われた番号からインクリメントされていきます (enumにおいて最後に陽に指定した値からインクリメントされていくのと同じです)。 つまりこういうことです:
# ---$1--- -$2- ---$6--- -$7- # | | | | | | | | m/ $1:=(food) (bard) $6:=(bazd) (quxd) /;
This "follow-on" behaviour is particularly useful for reinstituting Perl5 semantics for consecutive subpattern numbering in alternations:
この “follow-on”な振る舞いは、 選択におけるサブパターンの番号づけに Perl 5でのセマンティクスを 持ち込むのに便利です。
$tune_up = rx/ (don't) (ray) (me) (for) (solar tea), (d'oh!) | $6:=(every) (green) (BEM) (devours) (faces) # $7 $8 $9 $10 /;
It also provides an easy way in Perl 6 to reinstitute the unnested numbering semantics of nested Perl 5 subpatterns:
これはまた、Perl 6において ネストしているPerl 5のサブパターンのセマンティクスを ネストしてない番号付けに持ち込むのを簡単にします:
# Perl 5 の場合 # $1 # _____________/\______________ # | $2 $3 $4 | # | __/\___ ____/\____ /\ | # | | | | | | | | m/ ( (<[A..E]>) (\d**{3..6}) (X?) ) /;
# Perl 6 の場合 # $0 # _____________/\______________ # | $0[0] $0[1] $0[2] | # | __/\___ ____/\____ /\ | # | | | | | | | | m/ ( (<[A..E]>) (\d**{3..6}) (X?) ) /;
# Perl 6 simulating Perl 5... # Perl 5をシミュレートしたPerl 6の場合 # $1 # _______________/\________________ # | $2 $3 $4 | # | __/\___ ____/\____ /\ | # | | | | | | | | m/ $1:=[ (<[A..E]>) (\d**{3..6}) (X?) ] /;
The non-capturing brackets don't introduce a scope, so the subpatterns within
them are at rule scope, and hence numbered at the top level. Aliasing the
square brackets to $1
means that the next subpattern at the same level
(i.e. the (<[A..E]>)
) is numbered sequentially (i.e. $2
), etc.
捕獲を行わないブラケット対はスコープを持ち込まないので、
その中あるサブパターンはルールのスコープの中にあり、
したがって番号付けはトップレベルで行われます。
ブラケット対を$1
に別名付けすることによって
同じレベルにある次のサブパターン(この例では (<[A..E]>)
)は
連続した番号(つまり$2
)になります。
All of the above semantics apply equally to aliases which are bound to quantified structures.
これまで述べてきたセマンティクスは数量化された構造を束縛する 別名(エイリアス)に関して等しく適用されます。
The only difference is that, if the aliased construct is a subrule or
subpattern, that quantified subrule or subpattern will have returned a
list of Match
objects (as described in Quantified subpattern captures and Repeated captures of the same subrule).
So the corresponding array element or hash entry for the alias will
contain a reference to an array, instead of a single Match
object.
ただ一つ異なるのは、別名がつけられた構造がサブルール、もしくは
サブパターンであるときに、数量化されたサブルールやサブパターンは
Match
オブジェクトのリストを返すということです
(Quantified subpatterncaptures と
Repeated captures of the same subrule で説明したとおりです)。
そして別名に対応する配列要素やハッシュエントリは
単一のMatch
オブジェクトではなく、配列に対するリファレンスを
保持することになります。
In other words, aliasing and quantification are completely orthogonal. For example:
言い換えれば、別名をつけることと数量化することは完全に直交 (orthogonal)しているということです。 例を挙げましょう:
if m/ mv $0:=<file>+ / { # <file>+ returns a list of Match objects, # so $0 contains a reference to an array of Match objects, # one for each successful call to <file> # <file>+ はMatchオブジェクトのリストを返します # 結果として$0はMatchオブジェクトの配列のリファレンスを保持します # 要素のそれぞれは成功した<file>の呼び出しの結果です
# $/<file> does not exist (it's pre-empted by the alias) # $/<file> は存在しません(別名によって横取りされました) }
if m/ mv $<from>:=(\S+ \s+)* / { # Quantified subpattern returns a list of Match objects, # so $/<from> contains a reference to an array of Match # objects, one for each successful match of the subpattern # 数量化されたサブパターンはMatchオブジェクトのリストを返します # $/<from>はMatchオブジェクトの配列のリファレンスを保持し、 # ここの要素はサブパターンの成功したマッチの結果です
# $0 does not exist (it's pre-empted by the alias) # $0 は存在しません(別名によって横取りされました) }
Note, however, that a set of quantified non-capturing brackets always
returns a single Match
object which contains only the complete
substring that was matched by the full set of repetitions of the
brackets (as described in Named scalar aliases applied to non-capturing brackets). For example:
しかし、数量化された捕獲を行わない(non-capturing)ブラケット対は
常に、
繰り返し全体のブラケット対にマッチした部分文字列のみを保持する
単一のMatch
オブジェクトを返すということに注意してください
(Named scalar aliases applied to non-capturing brackets で説明したとおりです)。
例を挙げましょう:
"coffee fifo fumble" ~~ m/ $<effs>:=[f <-[f]>**{1..2} \s*]+ /;
say $<effs>; # prints "fee fifo fum"
An alias can also be specified using an array as the alias instead of scalar. For example:
別名付けは、スカラーの代わりに配列を使って指定することもできます。 例を挙げましょう:
m/ mv @<from>:=[(\S+) \s+]* <dir> /;
Using the @<alias>:=
notation instead of a $<alias>:=
mandates that the corresponding hash entry or array element always
receives a reference to an array of Match
objects, even if the
construct being aliased would normally return a single Match
object.
This is useful for creating consistent capture semantics across
structurally different alternations (by enforcing array captures in all
branches):
$<alias>:=
ではなく@<alias>:=
という表記を使うことによって
対応するハッシュエントリや配列要素は常にMatch
オブジェクトの
配列のリファレンスを受け取ります。
これは
別名をつけられた構造が
単一のMatch
オブジェクトを返したときもそうです。
これは
(すべての選択肢において配列による捕獲を強制させることによって)
異なる構造的な選択をまたいだ捕獲セマンティクスを
一貫させるときに便利です。
m:w/ Mr?s? @<names>:=<ident> W\. @<names>:=<ident> | Mr?s? @<names>:=<ident> /;
# Aliasing to @<names> means $/<names> is always # an array reference, so... # @<names> という別名をつけることにより$/<names>は常に # 配列リファレンスとなります。ですから…
say @{$/<names>};
For convenience and consistency, @<key>
can also be used outside a
regex, as a shorthand for @{ $/<key> }
. That is:
便利にするためと一貫性のために、@<key>
を
正規表現の外側で@{ $/<key>
の短縮表記として使うことができます。
つまりこういうことです:
m:w/ Mr?s? @<names>:=<ident> W\. @<names>:=<ident> | Mr?s? @<names>:=<ident> /;
say @<names>;
If an array alias is applied to a quantified pair of non-capturing brackets, it captures the substrings matched by each repetition of the brackets into separate elements of the corresponding array. That is:
配列による別名付けが捕獲を行わないブラケット対の数量化されたペアに 適用されたとき、そのブラケット対の個々の繰り返しにマッチした部分文字列は 捕獲されて対応する配列の別々の要素に送られます。 つまり:
m/ mv $<files>:=[ f.. \s* ]* /; # $/<files> assigned a single # Match object containing the # complete substring matched by # the full set of repetitions # of the non-capturing brackets # $/<files>は単一のC<Match>オブジェクトに割り当てられ、 # それは捕獲を行わないブラケット対の繰り返し # にマッチした部分文字列全部を保持します。
m/ mv @<files>:=[ f.. \s* ]* /; # $/<files> assigned an array, # each element of which is a # C<Match> object containing # the substring matched by Nth # repetition of the non- # capturing bracket match # $/<files> は配列に割り当てられ、 # その個々の要素はN番目の捕獲を行わない # ブラケット対にマッチした部分文字列を # 保持するC<Match>オブジェクトになります。
If an array alias is applied to a quantified pair of capturing parens
(i.e. to a subpattern), then the corresponding hash or array element is
assigned a list constructed by concatenating the array values of each
Match
object returned by one repetition of the subpattern. That is,
an array alias on a subpattern flattens and collects all nested
subpattern captures within the aliased subpattern. For example:
もし配列を使った別名付けが、
捕獲を行う括弧対
(つまりサブパターン)
のペアが数量化されたものに適用されたならば、
対応するハッシュ/配列の要素には
繰り返されたサブパターンにより返された個々のMatch
オブジェクトの
配列としての値を連結した構造をもつリストが代入されます。
つまり、
あるサブパターンに対する配列による別名付けは、
(別名がつけられたサブパターンの中にある)すべてのネストした
サブパターンによる捕獲を平滑化して集めたものになるということです。
例を挙げましょう:
if m:w/ $<pairs>:=( (\w+) \: (\N+) )+ / { # Scalar alias, so $/<pairs> is assigned an array # of Match objects, each of which has its own array # of two subcaptures... # スカラーによる別名付けなので、S/<pairs>にはMatchオブジェクトの # 配列が代入されます。この配列の要素はそれぞれ二つの副捕獲による # 配列を持っています…
for @{$<pairs>} -> $pair { say "Key: $pair[0]"; say "Val: $pair[1]"; } }
if m:w/ @<pairs>:=( (\w+) \: (\N+) )+ / { # Array alias, so $/<pairs> is assigned an array # of Match objects, each of which is flattened out of # the two subcaptures within the subpattern # 配列による別名付けなので、$/<pairs>にはMatchオブジェクトの # 配列が代入されます。この配列の要素はサブパターンによる # 副捕獲が平滑化されたものになります
for @{$<pairs>} -> $key, $val { say "Key: $key"; say "Val: $val"; } }
Likewise, if an array alias is applied to a quantified subrule, then the
hash or array element corresponding to the alias is assigned a list
containing the array values of each Match
object returned by each
repetition of the subrule, all flattened into a single array:
同様に、配列を使った別名付けが数量化されたサブルールに対して適用されたならば、
別名付けられたハッシュ/配列の要素には
サブルールの繰り返しによって返されたそれぞれのMatch
オブジェクトの値の
配列を保持するリストが代入されます。この配列は単一の配列へ平滑化されます。
rule pair :w { (\w+) \: (\N+) \n }
if m:w/ $<pairs>:=<pair>+ / { # Scalar alias, so $/<pairs> contains an array of # Match objects, each of which is the result of the # <pair> subrule call... # scalarによる別名付けなので、$/<pairs>はMatchオブジェクトの配列を # 保持します。配列の各要素には<pair>サブルールの呼び出しによる結果 # が入っています…
for @{$<pairs>} -> $pair { say "Key: $pair[0]"; say "Val: $pair[1]"; } }
if m:w/ mv @<pairs>:=<pair>+ / { # Array alias, so $/<pairs> contains an array of # Match objects, all flattened down from the # nested arrays inside the Match objects returned # by each match of the <pair> subrule... # 配列による別名付けなので、$/<pairs>はMatchオブジェクトの配列を # 保持します。<pair>サブルールにマッチした個々の戻り値としての # (ネストした配列である)Matchオブジェクトはすべて平滑化されます…
for @{$<pairs>} -> $key, $val { say "Key: $key"; say "Val: $val"; } }
In other words, an array alias is useful to flatten into a single array any nested captures that might occur within a quantified subpattern or subrule. Whereas a scalar alias is useful to preserve within a top-level array the internal structure of each repetition.
言い換えれば、配列による別名付けは 数量化されたサブパターンやサブルールの中で行われたかもしれない ネストした捕獲を単一の配列に平滑化するのに便利です。 一方スカラーによる別名付けは、 個々の繰り返しによる内部的な構造を保って トップレベルの配列をそのままにしておくのに便利です。
It is also possible to use a numbered variable as an array alias.
The semantics are exactly as described above, with the sole difference
being that the resulting array of Match
objects is assigned into the
appropriate element of the rule's match array, rather than to a key of
its match hash. For example:
配列による別名付けで番号変数(numberd variable)を使うこともできます。
そのセマンティクスは上で述べたものとまったく同じで、
ただ一つ異なるのは結果を収めるMatch
オブジェクトの配列が
ルールが持っているマッチハッシュの(該当する)キーの要素にではなく、
マッチ配列の適切な要素に代入されるという点です。
if m/ mv \s+ @0:=((\w+) \s+)+ $1:=((\W+) (\s*))* / { # | | # | | # | \_ Scalar alias, so $1 gets an # | array, with each element # | a Match object containing # | the two nested captures *1 # | # \___ Array alias, so $0 gets a flattened array of # just the (\w+) captures from each repetition *2
# *1 スカラーによる別名付けなので、$1は配列を得る。その配列の個々の # 要素は二つのネストした捕獲を保持しているMatchオブジェクトである
# *2 配列による別名付けなので、個々の繰り返しで行われた(\w+)によって # 捕獲されたものを平滑化した配列が$0になる。
@from = @{$0}; # Flattened list # 平滑化されたリスト
$to_str = $1[0][0]; # Nested elems of $to_gap = $1[0][1]; # unflattened list # 平滑化されていないリストのネストした要素 }
Note again that, outside a rule, @0
is simply a shorthand for
@{$0}
, so the first assignment above could also have been written:
繰り返しますが、ルールの外側では@0
は@{$0}
の単なる短縮表記なので
上記の例にある最初の代入は以下のように書くこともできるということに
注意してください。
@from = @0;
An alias can also be specified using a hash as the alias variable, instead of a scalar or an array. For example:
別名付けはスカラーや配列の他にも、 ハッシュを使って指定することもできます。 例を挙げましょう:
m/ mv %<location>:=( (<ident>) \: (\N+) )+ /;
A hash alias causes the correponding hash or array element in the
current scope's Match
object to be assigned a (nested) hash reference
(rather than an array reference or a single Match
object).
ハッシュによる別名付けはカレントのスコープにある
対応するMatch
オブジェクト中のハッシュ/配列の要素に
(ネストした)ハッシュリファレンスが代入されます
(配列リファレンスや単なるMatch
オブジェクトではありません)。
If a hash alias is applied to a subrule or subpattern then the first nested numeric capture becomes the key of each hash entry and any remaining numeric captures become the values (in an array if there is more than one),
ハッシュによる別名付けがサブルールやサブパターンに適用されたならば、 ネストした(数字による)捕獲の最初のものがハッシュのキーとなり、 残りのものがその値となります (二つ以上ものがあったら配列として)。
As with array aliases it is also possible to use a numbered variable as
a hash alias. Once again, the only difference is where the resulting
Match
object is stored:
配列による別名付けと同じように、
ハッシュによる別名付けとして番号変数を使うことができます。
もう一度繰り返しますが、番号変数を使ったときのただ一つの違いは
結果を収めているMatch
オブジェクトが格納される場所です:
rule one_to_many { (\w+) \: (\S+) (\S+) (\S+) }
if m:w/ %0:=<one_to_many>+ / { # $/[0] contains a hash, in which each key is provided by # the first subcapture within C<one_to_many>, and each # value is a reference to an array containing the # subrule's second, third, and fourth, etc. subcaptures... # $/[0] は各キーがC<one_to_many>の中で最初に捕獲された # ものがキーとなっていて、二番目以降に捕獲されたもののからなる # 配列のリファレンスが値となっているハッシュを保持している…
for %{$/[0]} -> $pair { say "One: $pair.key"; say "Many: { @{$pair.value} }"; } }
Outside the rule, %0
is a shortcut for %{$0}
:
ルールの外側では、%0
は%{$0}
の短縮表記です:
for %0 -> $pair { say "One: $pair.key"; say "Many: { @{$pair.value} }"; }
Instead of using internal aliases like:
以下のような内部的な別名の代わりに
m/ mv @<files>:=<ident>+ $<dir>:=<ident> /
the name of an ordinary variable can be used as an ȥxternal aliasɬ like so:
通常の変数名と同じように使うことのできる“外部エイリアス”(external alias) を使うことができます。ですから以下のように書くことができます:
m/ mv @files:=<ident>+ $dir:=<ident> /
In this case, the behaviour of each alias is exactly as described in the
previous sections, except that the resulting capture(s)
are bound
directly (but still hypothetically) to the variables of the specified
name that exist in the scope in which the rule declared.
この場合、個々のエイリアスの振る舞いは先述したものと同じです。 ただ一つ異なるのは、捕獲の結果が 宣言されたルールのスコープ中に存在する 名前によって指定された変数に 直接(それでもhypotheticalですが) 束縛されるという点です。
When an entire rule is successfully matched with repetitions
(specified via the :x
or :g
flag) or overlaps (specified via the
:ov
or :ex
flag), it will usually produce a series
of distinct matches.
あるルールの全体が
(:x
フラグや:g
フラグ付きで)
繰り返しを伴って成功したとき、
もしくは
(C:<ov>フラグや:ex
フラグ付きで)
オーバーラップして成功したとき、
通常それは異なるマッチの並びを生成します。
A successful match under any of these flags still returns a single
Match
object in $/
. However, the values of this match object are
slightly different from those provided by a non-repeated match:
これらのフラグがつけられた成功したマッチでも単一のMatch
オブジェクトが
$/
に返されます。しかし、このマッチオブジェクトの値は
繰り返しのないマッチによって生成されたものとは明らかに異なるものです。
The boolean value of $/
after such matches is true or false, depending on
whether the pattern matched.
$/
の(上記のフラグ指定がされた)マッチ後の論理値は
パターンマッチが成功したか失敗したかに応じてtrueもしくはfalseになります。
The string value is the substring from the start of the first match to the end of the last match (including any intervening parts of the string that the rule skipped over in order to find later matches).
文字列値は最初のマッチの開始位置から最後のマッチの終了位置までの 部分文字列(後続のマッチを見つけるためにルールがスキップした 文字列部分を含みます)。
There are no array contents or hash entries.
配列やハッシュを収めているエントリはありません。
For example:
例を挙げましょう:
if $text ~~ m:w:g/ (\S+:) <rocks> / { say 'Full match context is: [$/]'; }
The list of individual match objects corresponding to each separate
match is also available, via the .matches
method. For example:
個々のマッチに対応する独立したマッチオブジェクトのリストも
.matches
メソッドを使うことで使用可能です。
例を挙げましょう:
if $text ~~ m:w:g/ (\S+:) <rocks> / { say "Matched { +$/.matches } times";
for $/.matches -> $m { say "Match between $m.from() and $m.to()"; say 'Right on, dude!' if $m[0] eq 'Perl'; say "Rocks like $m<rocks>"; } }
:keepall
All rules remember everything if :keepall
is in effect
anywhere in the outer dynamic scope. In this case everything inside
the angles is used as part of the key. Suppose the earlier example
parsed whitespace:
外側の動的スコープ中において:keepall
が効果をもっているとき、
すべてのルールはすべてを覚えておきます。
この場合アングルブラケットの内側にあるすべてはキーの一部分として
使われます。空白を解析する先に挙げた例で考えてみましょう:
/ <key> <?ws> <'=>'> <?ws> <value> { %hash{$<key>} = $<value> } /
The two instances of <?ws>
above would store an array of two
values accessible as @<?ws>
. It would also store the literal
match into $<'=\>'>
. Just to make sure nothing is forgotten,
under :keepall
any text or whitespace not otherwise remembered is
attached as an extra property on the subsequent node. (The name of
that property is ȼcode>pretextɮ)
この例における二つの<?ws>
インスタンスは
@<?ws>
としてアクセスすることのできる二つの配列を
格納します。$<`=\>`>
でのリテラルマッチでも同様です。
忘れたものがないようにするために、:keepall
下のすべての
記憶されていない
テキスト/空白は
後続のノードにおける余計なプロパティのように添付されています
(そのプロパティは“pretext
”といいます)。
Your private ident
rule shouldn't clobber someone else's
ident
rule. So some mechanism is needed to confine rules to a namespace.
あなたの私的なident
ルールは他のident
ルールに影響を及ぼすべきではありません。
そのためいくつかの機構が名前空間にルールを分けるために必要です。
If subs are the model for rules, then modules/classes are the obvious model for aggregating them. Such collections of rules are generally known as ȧrammarsɮ
sub がルールのモデルであるなら、モジュール/クラスは それらを集めたモデルです。そのようなルールの集合は一般的には “文法”(grammars)として知られています。
Just as a class can collect named actions together:
クラスは単純に名前つきのアクションを一緒に集めることができます:
class Identity { method name { "Name = $.name" } method age { "Age = $.age" } method addr { "Addr = $.addr" }
method desc { print &.name(), "\n", &.age(), "\n", &.addr(), "\n"; }
# etc. }
so too a grammar can collect a set of named rules together:
ですから文法は名前付きルールの集合も一緒に集めることもできます:
grammar Identity { rule name :w { Name = (\N+) } rule age :w { Age = (\d+) } rule addr :w { Addr = (\N+) } rule desc { <name> \n <age> \n <addr> \n }
# etc. }
Like classes, grammars can inherit:
クラスと同様に、文法も継承できます:
grammar Letter { rule text { <greet> <body> <close> }
rule greet :w { [Hi|Hey|Yo] $<to>:=(\S+?) , $$}
rule body { <line>+ }
rule close :w { Later dude, $<from>:=(.+) }
# etc. }
grammar FormalLetter is Letter {
rule greet :w { Dear $<to>:=(\S+?) , $$}
rule close :w { Yours sincerely, $<from>:=(.+) }
}
Just like the methods of a class, the rule definitions of a grammar are
inherited (and polymorphic!). So there's no need to respecify body
,
line
, etc.
クラスにおけるメソッドのように、文法のルール定義は継承可能されます
(しかも多態(polymorphic)に!)。
ですから、body
やline
などを再度定義する必要はありません。
Perl 6 will come with at least one grammar predefined:
Perl 6 は少なくとも一つの定義済み文法を伴うでしょう:
grammar Perl { # Perl's own grammar # Perl自身の文法
rule prog { <statement>* }
rule statement { <decl> | <loop> | <label> [<cond>|<sideff>|;] }
rule decl { <sub> | <class> | <use> }
# etc. etc. etc. }
Hence:
given $source_code { $parsetree = m:keepall/<Perl.prog>/; }
For writing your own backslash and assertion rules or macros, you may use the following syntactic categories:
自分用のバックスラッシュルールや表明ルール、マクロを記述するために、 以下のような構文カテゴリを使用することができます:
rule rxbackslash:<w> { ... } # define your own \w and \W # オリジナルの \w と \W を定義 rule rxassertion:<*> { ... } # define your own <*stuff> # オリジナルの C<*stuff> を定義 macro rxmetachar:<,> { ... } # define a new metacharacter # 新たなメタキャラクタを定義 macro rxmodinternal:<x> { ... } # define your own /:x() stuff/ # オリジナルの /:x() stuff/ を定義 macro rxmodexternal:<x> { ... } # define your own m:x()/stuff/ # オリジナルの m:x()/stuff/ を定義
As with any such syntactic shenanigans, the declaration must be visible in the lexical scope to have any effect. It's possible the internal/external distinction is just a trait, and that some of those things are subs or methods rather than rules or macros. (The numeric rxmods are recognized by fallback macros defined with an empty operator name.)
任意のこのような構文的なshenanigans(ペテン?)を使うことで、 定義はそのレキシカルスコープで可視になり定められた効果をもちます。 internal/externalの区別は単なる特性で、 それらはルールやマクロではなくサブルーチンやメソッドです (数値的な rxmods は 空の演算子名を使って定義された フォールバックマクロによって認識されます)。
The rx
pragma may be used to control various aspects of regex
compilation and usage not otherwise provided for.
rx
プラグマは正規表現のコンパイルにおけるさまざまな様相や
提供されていない使い方を制御するために使うことができます。
The tr///
quote-like operator now also has a method form called
trans()
. Its argument is a list of pairs. You can use anything that
produces a pair list:
クォートに似た演算子 tr///
はtarns()
と呼ばれるメソッド形式も
持つようになりました。その引数はペアのリストです。
ペアのリストを生成するあらゆるものを使うことができます:
$str.trans( %mapping.pairs.sort );
Use the .= form to do a translation in place:
その場で変換を行うには .= 形式を使います:
$str.=trans( %mapping.pairs.sort );
The two sides of the any pair can be strings interpreted as tr///
would:
ペアの両端はtr///
が行うように解釈される文字列にすることができます:
$str.=trans( 'A..C' => 'a..c', 'XYZ' => 'xyz' );
As a degenerate case, each side can be individual characters:
degenerateな場合のように、両端には独立したキャラクタを置くこともできます:
$str.=trans( 'A'=>'a', 'B'=>'b', 'C'=>'c' );
The two sides of each pair may also be array references:
各ペアの両端を配列のリファレンスにすることもできます:
$str.=trans( ['A'..'C'] => ['a'..'c'], <X Y Z> => <x y z> );
The array version can map one-or-more characters to one-or-more characters:
配列バージョンのものは、一つ以上のキャラクタを一つ以上のキャラクタに マッピングすることが可能です:
$str.=trans( [' ', '<', '>', '&' ] => [' ', '<', '>', '&' ]);
In the case that more than one sequence of input characters matches, the longest one wins. In the case of two identical sequences the first in order wins.
入力されたキャラクタ群に対して複数のシーケンスがマッチした場合、 もっとも長いものが採用されます。 同じ長さのものが二つあった場合には最初に現れたものが採用されます。
There are also method forms of m//
and s///
:
m//
やs///
のメソッド形式のものもあります:
$str.match(//); $str.subst(//, "replacement") $str.subst(//, {"replacement"}) $str.=subst(//, "replacement") $str.=subst(//, {"replacement"})
Anything that can be tied to a string can be matched against a rule. This feature is particularly useful with input streams:
文字列に結びつける(tie)ことのできるものはなんでも あるルールに対してマッチングを試みることができます。 この機能は入力ストリームに関して特に便利でしょう:
my $stream is from($fh); # ファイルハンドルにスカラーを結びつける(tie)
# and later...
$stream ~~ m/pattern/; # ストリームに対するマッチ
An array can be matched against a rule. The special <,>
rule matches the boundary between elements. If the array elements
are strings, they are concatenated virtually into a single logical
string. If the array elements are tokens or other such objects, the
objects must provide appropriate methods for the kinds of rules to
match against. It is an assertion error to match a string-matching
assertion against an object that doesn't provide a string view.
However, pure token objects can be parsed as long as the match rule
restricts itself to assertions like:
配列をルールに対してマッチングさせることができます。
特殊なルール<,>
は要素の間の境界にマッチします。
もし配列要素が文字列であれば、それらは仮想的に連結されて
一つの論理的文字列(logical string)となります。
これらの配列要素がトークンかそれに類するオブジェクトであったならば、
そのオブジェクトはマッチを行うための
適切なメソッドを提供していなければなりません。
文字列のような見かけ(string view)を提供していないオブジェクトに対して
文字列マッチング表明(string-matching assertion)をしようとすると
表明エラーとなります。
しかしながら、純粋なトークンオブジェクトは
それ自身を表明するように制限されているマッチルールであるかのように解析されます:
<.isa(Dog)> <.does(Bark)> <.can('scratch')>
It is permissible to mix tokens and strings in an array as long as they're in different elements. You may not embed objects in strings, however.
トークンと文字列を一つの配列に混ぜて収めることは それらが異なる要素にあるのであれば可能です。 しかし、文字列の中にオブジェクトを埋め込むことは許されません。
To match against each element of an array, use a hyper operator:
ある配列の各要素に対してマッチングを行うにはhyper 演算子を使用します:
@array≫.match($rule)