<?xml version='1.0' encoding='utf-8'?>
<pod xmlns="http://axkit.org/ns/2000/pod2xml">
<head>
	<title>perlfaq4 - Data Manipulation ($Revision: 10394 $)</title>
</head>
<sect1>
<title>perlfaq4 - Data Manipulation ($Revision: 10394 $)</title>
<para>
perlfaq4 - データ操作 ($Revision: 10394 $)
</para>
</sect1>
<sect1>
<title>DESCRIPTION</title>
<para>
This section of the FAQ answers questions related to manipulating
numbers, dates, strings, arrays, hashes, and miscellaneous data issues.
</para>
<para>
FAQのこのセクションでは、数値、日付、文字列、配列、ハッシュその他の
データの取り扱いに関する質問に回答しています。
</para>
</sect1>
<sect1>
<title>Data: Numbers</title>
<para>
(データ: 数)
</para>
<sect2>
<title>Why am I getting long decimals (eg, 19.9499999999999) instead of the numbers I should be getting (eg, 19.95)?</title>
<para>
(なぜ 19.95 のような数字ではなく、19.9499999999999 のような長い数字が出てきたんでしょうか?)
</para>
<para>
Internally, your computer represents floating-point numbers in binary.
Digital (as in powers of two) computers cannot store all numbers
exactly.  Some real numbers lose precision in the process.  This is a
problem with how computers store numbers and affects all computer
languages, not just Perl.
</para>
<para>
内部的には、あなたの使っているコンピュータは浮動小数点数を 2 進数を
使って表現しています。
(2 のべき乗のような) デジタルなコンピュータは全ての数値を正確に
保管することはできません。
実数は処理中に精度が落ちることがあります。
これはコンピュータがどのように数値を保管するかの問題で、Perl だけではなく
全てのコンピュータ言語に影響を与えます。
</para>
<para>
<link xref='perlnumber'>perlnumber</link> shows the gory details of number representations and
conversions.
</para>
<para>
<link xref='perlnumber'>perlnumber</link> には、数値表現と変換に関する不愉快な詳細が記されています。
</para>
<para>
To limit the number of decimal places in your numbers, you can use the
printf or sprintf function.  See the <link xref='perlop'>&quot;Floating Point
Arithmetic&quot;</link> for more details.
</para>
<para>
10 進数の桁数を制限するには、printf や sprintf の関数が使えます。
更なる詳細については <link xref='perlop'>&quot;Floating Point Arithmetic&quot;</link> を参照してください。
</para>
<verbatim><![CDATA[
printf "%.2f", 10/3;
]]></verbatim>
<verbatim><![CDATA[
my $number = sprintf "%.2f", 10/3;
]]></verbatim>
</sect2>
<sect2>
<title>Why is int() broken?</title>
<para>
(なぜ int() は壊れているのでしょう?)
</para>
<para>
Your <code>int()</code> is most probably working just fine.  It's the numbers that
aren't quite what you think.
</para>
<para>
<code>int()</code> はほぼ確実に正しく動作しています。
これは、数値というものがあなたの考えているものと違うからです。
</para>
<para>
First, see the answer to &quot;Why am I getting long decimals
(eg, 19.9499999999999) instead of the numbers I should be getting
(eg, 19.95)?&quot;.
</para>
<para>
まず、&quot;Why am I getting long decimals
(eg, 19.9499999999999) instead of the numbers I should be getting
(eg, 19.95)?&quot; に対する答えを参照してください。
</para>
<para>
For example, this
</para>
<para>
例えば、これは:
</para>
<verbatim><![CDATA[
print int(0.6/0.2-2), "\n";
]]></verbatim>
<para>
will in most computers print 0, not 1, because even such simple
numbers as 0.6 and 0.2 cannot be presented exactly by floating-point
numbers.  What you think in the above as 'three' is really more like
2.9999999999999995559.
</para>
<para>
ほとんどのコンピュータでは 1 ではなく 0 を表示します;
0.6 や 0.2 と言った単純な数値であっても、浮動小数点数で正確に表現できません。
さきほどあなたが &quot;3&quot; と考えたものは、実際には 2.9999999999999995559 と
いったものです。
</para>
</sect2>
<sect2>
<title>Why isn't my octal data interpreted correctly?</title>
<para>
(なぜ私の 8 進データは正しく解釈されないのでしょうか?)
</para>
<para>
Perl only understands octal and hex numbers as such when they occur as
literals in your program.  Octal literals in perl must start with a
leading <code>0</code> and hexadecimal literals must start with a leading <code>0x</code>.
If they are read in from somewhere and assigned, no automatic
conversion takes place.  You must explicitly use <code>oct()</code> or <code>hex()</code> if you
want the values converted to decimal.  <code>oct()</code> interprets hexadecimal (<code>0x350</code>),
octal (<code>0350</code> or even without the leading <code>0</code>, like <code>377</code>) and binary
(<code>0b1010</code>) numbers, while <code>hex()</code> only converts hexadecimal ones, with
or without a leading <code>0x</code>, such as <code>0x255</code>, <code>3A</code>, <code>ff</code>, or <code>deadbeef</code>.
The inverse mapping from decimal to octal can be done with either the
&lt;%o&gt; or <code>%O</code> <code>sprintf()</code> formats.
</para>
<para>
Perl は、プログラムの中にリテラルとして現れたときにだけ 8 進数や 16 進数を
理解します。
perl での 8 進数リテラルは先頭に <code>0</code> が必要で、16 進数リテラルは
先頭に <code>0x</code> が必要です。
それらのものがそれ以外の場所からとか代入で読み込まれた場合、
変換は実行されません。
10 進数へ変換したいなら、陽に <code>oct()</code> や <code>hex()</code> を使わなければなりません。
<code>oct()</code> は 16 進数(<code>0x350</code>)、8 進数(<code>0350</code> や、<code>377</code> のように
先頭の <code>0</code> がないものでも)、2 進数(<code>0b1010</code>) を解釈するのに対して、
hex() が 16 進数(<code>0x255</code>, <code>3A</code>, <code>ff</code>, <code>deadbeef</code> のように、
先頭に <code>0x</code> がついたりつかなかったりします)のみを変換します。
10 進数から 8 進数への逆変換は <code>sprintf()</code> の &lt;%o&gt; か <code>%O</code> の
フォーマットで行えます。
</para>
<para>
This problem shows up most often when people try using <code>chmod()</code>,
<code>mkdir()</code>, <code>umask()</code>, or <code>sysopen()</code>, which by widespread tradition
typically take permissions in octal.
</para>
<para>
この問題は、パーミッションを 8 進数で指定するような広く広まった
伝統のために <code>chmod()</code>, <code>mkdir()</code>, <code>umask()</code>, <code>sysopen()</code> を使おうと
したときによく発生します。
</para>
<verbatim><![CDATA[
chmod(644,  $file);   # WRONG
chmod(0644, $file);   # right
]]></verbatim>
<para>
Note the mistake in the first line was specifying the decimal literal
<code>644</code>, rather than the intended octal literal <code>0644</code>.  The problem can
be seen with:
</para>
<para>
1 行目の間違いは、意図している 8 進数リテラル <code>0644</code> ではなく、
10 進数 リテラル <code>644</code> を指定していることであることに注意してください。
問題点は、以下のようにすることで見られます:
</para>
<verbatim><![CDATA[
printf("%#o",644);   # prints 01204
]]></verbatim>
<para>
Surely you had not intended <code>chmod(01204, $file);</code> - did you?  If you
want to use numeric literals as arguments to chmod() et al. then please
try to express them as octal constants, that is with a leading zero and
with the following digits restricted to the set <code>0..7</code>.
</para>
<para>
きっと <code>chmod(01204, $file);</code> は意図してないはずです - ですよね?
chmod() などでの引数として数値リテラルを使いたい場合は、
先頭に 0 をつけ、その後に <code>0..7</code> の数値が続く 8 進定数を使うように
してください。
</para>
</sect2>
<sect2>
<title>Does Perl have a round() function?  What about ceil() and floor()?  Trig functions?</title>
<para>
(Perl には丸め関数がありますか? ceil() と floor() とは何ですか? 三角関数は?)
</para>
<para>
Remember that <code>int()</code> merely truncates toward 0.  For rounding to a
certain number of digits, <code>sprintf()</code> or <code>printf()</code> is usually the
easiest route.
</para>
<para>
<code>int()</code> は 0 へ向かって丸めを行うことを思い出してください。
特定の桁数で丸めを行うには、<code>sprintf()</code> や <code>printf()</code> を使うことが
通常はもっとも簡単なやり方です。
</para>
<verbatim><![CDATA[
printf("%.3f", 3.1415926535);   # prints 3.142
]]></verbatim>
<para>
The <code>POSIX</code> module (part of the standard Perl distribution)
implements <code>ceil()</code>, <code>floor()</code>, and a number of other mathematical
and trigonometric functions.
</para>
<para>
(標準 Perl 配布キットの一部である)<code>POSIX</code> モジュールは <code>ceil()</code>、
<code>floor()</code>、そしてその他の数学的な関数や三角関数の多くを実装しています。
</para>
<verbatim><![CDATA[
use POSIX;
$ceil   = ceil(3.5);   # 4
$floor  = floor(3.5);  # 3
]]></verbatim>
<para>
In 5.000 to 5.003 perls, trigonometry was done in the <code>Math::Complex</code>
module.  With 5.004, the <code>Math::Trig</code> module (part of the standard Perl
distribution) implements the trigonometric functions. Internally it
uses the <code>Math::Complex</code> module and some functions can break out from
the real axis into the complex plane, for example the inverse sine of
2.
</para>
<para>
perl の 5.000 から 5.003 では、三角関数は <code>Math::Complex</code> モジュールの中で
実行されていました。
5.004 では、<code>Math::Trig</code> モジュール(標準 Perl 配布キットの一部です)が
三角関数を実装しています。
内部的にはこれは <code>Math::Complex</code> を使っていて、一部の関数は実数値を複素数領域へ
変化させることができます。
2 の inverse sine がその一例です。
</para>
<para>
Rounding in financial applications can have serious implications, and
the rounding method used should be specified precisely.  In these
cases, it probably pays not to trust whichever system rounding is
being used by Perl, but to instead implement the rounding function you
need yourself.
</para>
<para>
金融に関係するアプリケーションにおいては、丸めはきちんとした実装を
必要とするかもしれません。
そして、丸めの方法は適切に使われるべきものです。
この場合、Perl が使っているシステムによる丸めを信用すべきではなく、
自分自身で丸め関数を実装するようにすべきでしょう。
</para>
<para>
To see why, notice how you'll still have an issue on half-way-point
alternation:
</para>
<para>
なぜかを見るために、中間点反復に関する問題があるということに注意しましょう:
</para>
<verbatim><![CDATA[
for ($i = 0; $i < 1.01; $i += 0.05) { printf "%.1f ",$i}
]]></verbatim>
<verbatim><![CDATA[
0.0 0.1 0.1 0.2 0.2 0.2 0.3 0.3 0.4 0.4 0.5 0.5 0.6 0.7 0.7
0.8 0.8 0.9 0.9 1.0 1.0
]]></verbatim>
<para>
Don't blame Perl.  It's the same as in C.  IEEE says we have to do
this. Perl numbers whose absolute values are integers under 2**31 (on
32 bit machines) will work pretty much like mathematical integers.
Other numbers are not guaranteed.
</para>
<para>
Perl を責めないでください。
これはCでも同じことなのです。
IEEE ではこのようにすることを述べています。
Perl での数値は絶対値で 2**31(32 ビットマシンの場合)以下の場合の整数値であれば
数学的な整数と同じように振る舞います。
それ以外の数値は恩恵を受けません。
</para>
</sect2>
<sect2>
<title>How do I convert between numeric representations/bases/radixes?</title>
<para>
(数値表現や基底や基数を変換するには?)
</para>
<para>
As always with Perl there is more than one way to do it.  Below are a
few examples of approaches to making common conversions between number
representations.  This is intended to be representational rather than
exhaustive.
</para>
<para>
Perl ではいつものことですが、これを行うには複数の方法があります。
以下は、一般的な数値表現の変換を行うための手法のいくつかの例です。
これは完全性よりも説明性を意図しています。
</para>
<para>
Some of the examples later in <link xref='perlfaq4'>perlfaq4</link> use the <code>Bit::Vector</code>
module from CPAN. The reason you might choose <code>Bit::Vector</code> over the
perl built in functions is that it works with numbers of ANY size,
that it is optimized for speed on some operations, and for at least
some programmers the notation might be familiar.
</para>
<para>
<link xref='perlfaq4'>perlfaq4</link> の後の方での例では CPAN にある <code>Bit::Vector</code> を使っています。
perl 組み込みの関数よりも <code>Bit::Vector</code> を選択する理由は、
どんな大きさの数でも動作し、いくつかの操作では速度のために最適化されていて、
少なくともいくらかのプログラマにとっては表記がわかりやすいからです。
</para>
<list>
<item><itemtext>How do I convert hexadecimal into decimal</itemtext>
<para>
(16 進数を 10 進数に変換するには?)
</para>
<para>
Using perl's built in conversion of <code>0x</code> notation:
</para>
<para>
<code>0x</code> 表記による perl の組み込み変換を使って:
</para>
<verbatim><![CDATA[
$dec = 0xDEADBEEF;
]]></verbatim>
<para>
Using the <code>hex</code> function:
</para>
<para>
<code>hex</code> 関数を使って:
</para>
<verbatim><![CDATA[
$dec = hex("DEADBEEF");
]]></verbatim>
<para>
Using <code>pack</code>:
</para>
<para>
<code>pack</code> を使って:
</para>
<verbatim><![CDATA[
$dec = unpack("N", pack("H8", substr("0" x 8 . "DEADBEEF", -8)));
]]></verbatim>
<para>
Using the CPAN module <code>Bit::Vector</code>:
</para>
<para>
CPAN の <code>Bit::Vector</code> モジュールを使って:
</para>
<verbatim><![CDATA[
use Bit::Vector;
$vec = Bit::Vector->new_Hex(32, "DEADBEEF");
$dec = $vec->to_Dec();
]]></verbatim>
</item>
<item><itemtext>How do I convert from decimal to hexadecimal</itemtext>
<para>
(10 進数を 16 進数に変換するには?)
</para>
<para>
Using <code>sprintf</code>:
</para>
<para>
<code>sprintf</code> を使って:
</para>
<verbatim><![CDATA[
$hex = sprintf("%X", 3735928559); # upper case A-F
$hex = sprintf("%x", 3735928559); # lower case a-f
]]></verbatim>
<para>
Using <code>unpack</code>:
</para>
<para>
<code>unpack</code> を使って:
</para>
<verbatim><![CDATA[
$hex = unpack("H*", pack("N", 3735928559));
]]></verbatim>
<para>
Using <code>Bit::Vector</code>:
</para>
<para>
<code>Bit::Vector</code> を使って:
</para>
<verbatim><![CDATA[
use Bit::Vector;
$vec = Bit::Vector->new_Dec(32, -559038737);
$hex = $vec->to_Hex();
]]></verbatim>
<para>
And <code>Bit::Vector</code> supports odd bit counts:
</para>
<para>
そして <code>Bit::Vector</code> は半端なビット数にも対応しています:
</para>
<verbatim><![CDATA[
use Bit::Vector;
$vec = Bit::Vector->new_Dec(33, 3735928559);
$vec->Resize(32); # suppress leading 0 if unwanted
$hex = $vec->to_Hex();
]]></verbatim>
</item>
<item><itemtext>How do I convert from octal to decimal</itemtext>
<para>
(8 進数を 10 進数に変換するには?)
</para>
<para>
Using Perl's built in conversion of numbers with leading zeros:
</para>
<para>
先頭に 0 を付けることによる Perl 組み込みの変換を使って:
</para>
<verbatim><![CDATA[
$dec = 033653337357; # note the leading 0!
]]></verbatim>
<para>
Using the <code>oct</code> function:
</para>
<para>
<code>oct</code> function 関数を使って:
</para>
<verbatim><![CDATA[
$dec = oct("33653337357");
]]></verbatim>
<para>
Using <code>Bit::Vector</code>:
</para>
<para>
<code>Bit::Vector</code> を使って:
</para>
<verbatim><![CDATA[
use Bit::Vector;
$vec = Bit::Vector->new(32);
$vec->Chunk_List_Store(3, split(//, reverse "33653337357"));
$dec = $vec->to_Dec();
]]></verbatim>
</item>
<item><itemtext>How do I convert from decimal to octal</itemtext>
<para>
(10 進数を 8 進数に変換するには?)
</para>
<para>
Using <code>sprintf</code>:
</para>
<para>
<code>sprintf</code> を使って:
</para>
<verbatim><![CDATA[
$oct = sprintf("%o", 3735928559);
]]></verbatim>
<para>
Using <code>Bit::Vector</code>:
</para>
<para>
<code>Bit::Vector</code> を使って:
</para>
<verbatim><![CDATA[
use Bit::Vector;
$vec = Bit::Vector->new_Dec(32, -559038737);
$oct = reverse join('', $vec->Chunk_List_Read(3));
]]></verbatim>
</item>
<item><itemtext>How do I convert from binary to decimal</itemtext>
<para>
(2 進数から 10 進数に変換するには?)
</para>
<para>
Perl 5.6 lets you write binary numbers directly with
the <code>0b</code> notation:
</para>
<para>
Perl 5.6 から、<code>0b</code> 表記を使って直接 2 進数を書くことができます:
</para>
<verbatim><![CDATA[
$number = 0b10110110;
]]></verbatim>
<para>
Using <code>oct</code>:
</para>
<para>
<code>oct</code> を使って:
</para>
<verbatim><![CDATA[
my $input = "10110110";
$decimal = oct( "0b$input" );
]]></verbatim>
<para>
Using <code>pack</code> and <code>ord</code>:
</para>
<para>
<code>pack</code> と <code>ord</code> を使って:
</para>
<verbatim><![CDATA[
$decimal = ord(pack('B8', '10110110'));
]]></verbatim>
<para>
Using <code>pack</code> and <code>unpack</code> for larger strings:
</para>
<para>
より大きな文字列に対しては、<code>pack</code> と <code>unpack</code> を使って:
</para>
<verbatim><![CDATA[
$int = unpack("N", pack("B32",
substr("0" x 32 . "11110101011011011111011101111", -32)));
$dec = sprintf("%d", $int);
]]></verbatim>
<verbatim><![CDATA[
# substr() is used to left pad a 32 character string with zeros.
]]></verbatim>
<para>
Using <code>Bit::Vector</code>:
</para>
<para>
<code>Bit::Vector</code> を使って:
</para>
<verbatim><![CDATA[
$vec = Bit::Vector->new_Bin(32, "11011110101011011011111011101111");
$dec = $vec->to_Dec();
]]></verbatim>
</item>
<item><itemtext>How do I convert from decimal to binary</itemtext>
<para>
Using <code>sprintf</code> (perl 5.6+):
</para>
<para>
<code>sprintf</code> を使って(perl 5.6 以降):
</para>
<verbatim><![CDATA[
$bin = sprintf("%b", 3735928559);
]]></verbatim>
<para>
Using <code>unpack</code>:
</para>
<para>
<code>unpack</code> を使って:
</para>
<verbatim><![CDATA[
$bin = unpack("B*", pack("N", 3735928559));
]]></verbatim>
<para>
Using <code>Bit::Vector</code>:
</para>
<para>
<code>Bit::Vector</code> を使って:
</para>
<verbatim><![CDATA[
use Bit::Vector;
$vec = Bit::Vector->new_Dec(32, -559038737);
$bin = $vec->to_Bin();
]]></verbatim>
<para>
The remaining transformations (e.g. hex -&gt; oct, bin -&gt; hex, etc.)
are left as an exercise to the inclined reader.
</para>
<para>
残りの変換 (16 進 -&gt; 8 進、2 進 -&gt; 16 進、など) は読者への宿題として
残しておきます。
</para>
</item>
</list>
</sect2>
<sect2>
<title>Why doesn't &amp; work the way I want it to?</title>
<para>
(なぜ &amp; は私の思った通りに動作しないのでしょうか?)
</para>
<para>
The behavior of binary arithmetic operators depends on whether they're
used on numbers or strings.  The operators treat a string as a series
of bits and work with that (the string <code>&quot;3&quot;</code> is the bit pattern
<code>00110011</code>).  The operators work with the binary form of a number
(the number <code>3</code> is treated as the bit pattern <code>00000011</code>).
</para>
<para>
バイナリ算術演算子の振る舞いはそれが数値に対して使われているのか
文字列に対して使われているかということに依存しています。
その演算子は文字列をビットの並びとして扱います(<code>&quot;3&quot;</code> という文字列は
<code>00110011</code> というビットパターンとなります)。
この演算子はバイナリ形式に対して働きます
(<code>3</code> という数値は <code>00000011</code> というビットパターンとして扱われます)。
</para>
<para>
So, saying <code>11 &amp; 3</code> performs the &quot;and&quot; operation on numbers (yielding
<code>3</code>).  Saying <code>&quot;11&quot; &amp; &quot;3&quot;</code> performs the &quot;and&quot; operation on strings
(yielding <code>&quot;1&quot;</code>).
</para>
<para>
ですから、<code>11 &amp; 3</code> は数値に対する &quot;and&quot; として働きます(結果は
<code>3</code> です)。
<code>&quot;11&quot; &amp; &quot;3&quot;</code>は文字列に対する &quot;and&quot; として働きます(結果は <code>&quot;1&quot;</code> です)。
</para>
<para>
Most problems with <code>&amp;</code> and <code>|</code> arise because the programmer thinks
they have a number but really it's a string.  The rest arise because
the programmer says:
</para>
<para>
ありがちな問題は <code>&amp;</code> と <code>|</code> を使ったときに、プログラマは
オペランドが数値と考えているのに実際は文字列であるようなときに
起こります。
例を挙げましょう:
</para>
<verbatim><![CDATA[
if ("\020\020" & "\101\101") {
	# ...
	}
]]></verbatim>
<para>
but a string consisting of two null bytes (the result of <code>&quot;\020\020&quot;
&amp; &quot;\101\101&quot;</code>) is not a false value in Perl.  You need:
</para>
<para>
この場合の結果は二つのナルバイトを含む文字列となります
(<code>&quot;\020\020&quot;</code> の結果です)が、これは Perl における偽の値では
ありません。
以下のようにする必要があります:
</para>
<verbatim><![CDATA[
if ( ("\020\020" & "\101\101") !~ /[^\000]/) {
	# ...
	}
]]></verbatim>
</sect2>
<sect2>
<title>How do I multiply matrices?</title>
<para>
(行列の積を計算するには?)
</para>
<para>
Use the Math::Matrix or Math::MatrixReal modules (available from CPAN)
or the PDL extension (also available from CPAN).
</para>
<para>
Math::Matrix モジュールか、Math::MatrixReal モジュール(CPAN で入手できます)か
PDL エクステンション(これも CPAN で入手できます)を使います。
</para>
</sect2>
<sect2>
<title>How do I perform an operation on a series of integers?</title>
<para>
(整数値の並びに対してある操作を実行するには?)
</para>
<para>
To call a function on each element in an array, and collect the
results, use:
</para>
<para>
配列の各要素に対して関数を呼び出して、結果を集めるにはこうします:
</para>
<verbatim><![CDATA[
@results = map { my_func($_) } @array;
]]></verbatim>
<para>
For example:
</para>
<para>
例えば:
</para>
<verbatim><![CDATA[
@triple = map { 3 * $_ } @single;
]]></verbatim>
<para>
To call a function on each element of an array, but ignore the
results:
</para>
<para>
配列の各要素に対して関数を呼び出すけれども、結果を無視するという
場合にはこうします:
</para>
<verbatim><![CDATA[
foreach $iterator (@array) {
	some_func($iterator);
	}
]]></verbatim>
<para>
To call a function on each integer in a (small) range, you <strong>can</strong> use:
</para>
<para>
ある(小さな)範囲にある整数に対して関数を呼び出すには、こうも <strong>できます</strong>:
</para>
<verbatim><![CDATA[
@results = map { some_func($_) } (5 .. 25);
]]></verbatim>
<para>
but you should be aware that the <code>..</code> operator creates an array of
all integers in the range.  This can take a lot of memory for large
ranges.  Instead use:
</para>
<para>
ただし、<code>..</code> 演算子がその範囲にあるすべての整数の配列を生成するということに
注意すべきでしょう。
これによって大きな範囲を使った場合に大量のメモリを消費することになります。
代わりにこうします:
</para>
<verbatim><![CDATA[
@results = ();
for ($i=5; $i < 500_005; $i++) {
	push(@results, some_func($i));
	}
]]></verbatim>
<para>
This situation has been fixed in Perl5.005. Use of <code>..</code> in a <code>for</code>
loop will iterate over the range, without creating the entire range.
</para>
<para>
この状況は Perl5.005 で修正されました。
<code>for</code> ループで <code>..</code> を使うことで、
範囲全体を生成することなく特定の範囲の繰り返しを行えます。
</para>
<verbatim><![CDATA[
for my $i (5 .. 500_005) {
	push(@results, some_func($i));
	}
]]></verbatim>
<para>
will not create a list of 500,000 integers.
</para>
<para>
このようにしても 500,000 個の整数のリストが生成されたりはしません。
</para>
</sect2>
<sect2>
<title>How can I output Roman numerals?</title>
<para>
(ローマ数字を出力するには?)
</para>
<para>
Get the <xlink uri='http://www.cpan.org/modules/by-module/Roman'>http://www.cpan.org/modules/by-module/Roman</xlink> module.
</para>
<para>
<xlink uri='http://www.cpan.org/modules/by-module/Roman'>http://www.cpan.org/modules/by-module/Roman</xlink> モジュールを入手しましょう。
</para>
</sect2>
<sect2>
<title>Why aren't my random numbers random?</title>
<para>
(なぜ私の乱数はランダムでないの?)
</para>
<para>
If you're using a version of Perl before 5.004, you must call <code>srand</code>
once at the start of your program to seed the random number generator.
</para>
<para>
5.004 より前のバージョンの Perl を使っているなら、<code>srand</code> を
プログラムの開始時点で一度呼び出してやって、乱数生成器の種を
セットしてやらなければなりません。
</para>
<verbatim><![CDATA[
BEGIN { srand() if $] < 5.004 }
]]></verbatim>
<para>
5.004 and later automatically call <code>srand</code> at the beginning.  Don't
call <code>srand</code> more than once--you make your numbers less random,
rather than more.
</para>
<para>
5.004 以降のものでは開始時点で自動的に <code>srand</code> を呼び出します。
二度以上 <code>srand</code> を呼び出してはいけません。
乱数の質を落としてしまいます。
</para>
<para>
Computers are good at being predictable and bad at being random
(despite appearances caused by bugs in your programs :-).  see the
<filename>random</filename> article in the &quot;Far More Than You Ever Wanted To Know&quot;
collection in <xlink uri='http://www.cpan.org/misc/olddoc/FMTEYEWTK.tgz'>http://www.cpan.org/misc/olddoc/FMTEYEWTK.tgz</xlink> , courtesy
of Tom Phoenix, talks more about this.  John von Neumann said, &quot;Anyone
who attempts to generate random numbers by deterministic means is, of
course, living in a state of sin.&quot;
</para>
<para>
コンピュータは予測できる物事に関しては役に立ちますが、ランダムな
ことに対してはそうではありません(それはあなたのプログラム自身のバグによって
引き起こされることですが:-)
Tom Phoenix がこの問題について語っている、
<xlink uri='http://www.cpan.org/misc/olddoc/FMTEYEWTK.tgz'>http://www.cpan.org/misc/olddoc/FMTEYEWTK.tgz</xlink>
の &quot;Far More Than You Ever Wanted To Know&quot; の中の <filename>random</filename> という記事を
参照してください。
ジョン・フォン・ノイマン曰く、「決定論的手段によって
乱数を作ろうと試みる全ての人はもちろん罪深きものである。」
</para>
<para>
If you want numbers that are more random than <code>rand</code> with <code>srand</code>
provides, you should also check out the <code>Math::TrulyRandom</code> module from
CPAN.  It uses the imperfections in your system's timer to generate
random numbers, but this takes quite a while.  If you want a better
pseudorandom generator than comes with your operating system, look at
&quot;Numerical Recipes in C&quot; at <xlink uri='http://www.nr.com/'>http://www.nr.com/</xlink> .
</para>
<para>
<code>rand</code> と <code>srand</code> が提供するものよりもよりランダムな数値が必要なら、
CPAN にある <code>Math::TrulyRandom</code> モジュールも
チェックしてみると良いでしょう。
これはあなたの使っているシステムのタイマーを乱数を生成するのに
使っていて不完全な面もありますが、十分なものです。
あなたの使うオペレーティングシステムで使えるものよりも
もっと良質な擬似乱数を必要としているのなら、
<xlink uri='http://www.nr.com'>http://www.nr.com</xlink> にある ``Numerical Recipes in C'' を見るとよいでしょう。
</para>
</sect2>
<sect2>
<title>How do I get a random number between X and Y?</title>
<para>
(X と Y の間の乱数を得るには?)
</para>
<para>
To get a random number between two values, you can use the <code>rand()</code>
builtin to get a random number between 0 and 1. From there, you shift
that into the range that you want.
</para>
<para>
二つの値の間の乱数を得るためには、まず 0 と 1 との間の乱数を得るために
<code>rand()</code> 組み込み関数を使います。
それから、これを必要な範囲にシフトします。
</para>
<para>
<code>rand($x)</code> returns a number such that <code>0 &lt;= rand($x) &lt; $x</code>. Thus
what you want to have perl figure out is a random number in the range
from 0 to the difference between your <emphasis>X</emphasis> and <emphasis>Y</emphasis>.
</para>
<para>
<code>rand($x)</code> は <code>0 &lt;= rand($x) &lt; $x</code> という値を返します。
従って、perl に作ってほしいものは、0 から、必要な <emphasis>X</emphasis> と <emphasis>Y</emphasis> との差
までの範囲の乱数です。
</para>
<para>
That is, to get a number between 10 and 15, inclusive, you want a
random number between 0 and 5 that you can then add to 10.
</para>
<para>
つまり、10 から 15 の範囲の値(両端を含む) を得るためには、
0 から 5 の範囲の乱数を求めて、それに 10 を加えます。
</para>
<verbatim><![CDATA[
my $number = 10 + int rand( 15-10+1 );
]]></verbatim>
<para>
Hence you derive the following simple function to abstract
that. It selects a random integer between the two given
integers (inclusive), For example: <code>random_int_between(50,120)</code>.
</para>
<para>
従って、これを抽象化するために以下のサンプル関数を導き出します。
これは与えられた二つの整数を含む範囲のランダムな整数を選択します。
例えば: <code>random_int_between(50,120)</code>
</para>
<verbatim><![CDATA[
sub random_int_between {
	my($min, $max) = @_;
	# Assumes that the two arguments are integers themselves!
	return $min if $min == $max;
	($min, $max) = ($max, $min)  if  $min > $max;
	return $min + int rand(1 + $max - $min);
	}
]]></verbatim>
</sect2>
</sect1>
<sect1>
<title>Data: Dates</title>
<para>
(データ:日付)
</para>
<sect2>
<title>How do I find the day or week of the year?</title>
<para>
(その年の何日目であるかを知るには?)
</para>
<para>
The localtime function returns the day of the year.  Without an
argument localtime uses the current time.
</para>
<para>
localtime 関数はその年の何日目であるかを返します。
引数なしの localtime は現在時刻を使います。
</para>
<verbatim><![CDATA[
$day_of_year = (localtime)[7];
]]></verbatim>
<para>
The <code>POSIX</code> module can also format a date as the day of the year or
week of the year.
</para>
<para>
<code>POSIX</code> モジュールも日付をその年の何日目か、または何週目かに整形します。
</para>
<verbatim><![CDATA[
use POSIX qw/strftime/;
my $day_of_year  = strftime "%j", localtime;
my $week_of_year = strftime "%W", localtime;
]]></verbatim>
<para>
To get the day of year for any date, use <code>POSIX</code>'s <code>mktime</code> to get
a time in epoch seconds for the argument to localtime.
</para>
<para>
任意の日付に対してその年の何日目かを得るには、localtime の引数から
紀元からの秒数を求めるために、<code>POSIX</code> の <code>mktime</code> を使います。
</para>
<verbatim><![CDATA[
use POSIX qw/mktime strftime/;
my $week_of_year = strftime "%W",
	localtime( mktime( 0, 0, 0, 18, 11, 87 ) );
]]></verbatim>
<para>
The <code>Date::Calc</code> module provides two functions to calculate these.
</para>
<para>
<code>Date::Calc</code> モジュールはこれらを計算する二つの関数を提供します。
</para>
<verbatim><![CDATA[
use Date::Calc;
my $day_of_year  = Day_of_Year(  1987, 12, 18 );
my $week_of_year = Week_of_Year( 1987, 12, 18 );
]]></verbatim>
</sect2>
<sect2>
<title>How do I find the current century or millennium?</title>
<para>
(現在の世紀や千年紀を知るには?)
</para>
<para>
Use the following simple functions:
</para>
<para>
以下の単純な関数を使ってください:
</para>
<verbatim><![CDATA[
sub get_century    {
	return int((((localtime(shift || time))[5] + 1999))/100);
	}
]]></verbatim>
<verbatim><![CDATA[
sub get_millennium {
	return 1+int((((localtime(shift || time))[5] + 1899))/1000);
	}
]]></verbatim>
<para>
On some systems, the <code>POSIX</code> module's <code>strftime()</code> function has been
extended in a non-standard way to use a <code>%C</code> format, which they
sometimes claim is the &quot;century&quot;. It isn't, because on most such
systems, this is only the first two digits of the four-digit year, and
thus cannot be used to reliably determine the current century or
millennium.
</para>
<para>
システムによっては、<code>POSIX</code> モジュールの <code>strftime()</code> 関数が
非標準の方法で <code>%C</code> フォーマット(&quot;century&quot;だと主張されることがあります)を
使うように拡張されているかもしれません。
これは世紀ではありません。
なぜならこのようなシステムのほとんどでは、
これは 4 桁の年の上位 2 桁を示しているだけなので、
現在の世紀や千年紀を決定する信頼できる方法ではありません。
</para>
</sect2>
<sect2>
<title>How can I compare two dates and find the difference?</title>
<para>
(二つの日付文字列を比較するには?)
</para>
<para>
(contributed by brian d foy)
</para>
<para>
(brian d foy によって寄贈されました)
</para>
<para>
You could just store all your dates as a number and then subtract.
Life isn't always that simple though. If you want to work with
formatted dates, the <code>Date::Manip</code>, <code>Date::Calc</code>, or <code>DateTime</code>
modules can help you.
</para>
<para>
日付を単に数値として保管して、それから引き算することもできます。
しかし、人生はいつもこんな風に単純とは限りません。
フォーマットされた日付に対して作業したい場合は、
<code>Date::Manip</code>, <code>Date::Calc</code>, <code>DateTime</code> といったモジュールが
助けになるかもしれません。
</para>
</sect2>
<sect2>
<title>How can I take a string and turn it into epoch seconds?</title>
<para>
(文字列を受け取って、それを紀元からの経過秒数に変換するには?)
</para>
<para>
If it's a regular enough string that it always has the same format,
you can split it up and pass the parts to <code>timelocal</code> in the standard
<code>Time::Local</code> module.  Otherwise, you should look into the <code>Date::Calc</code>
and <code>Date::Manip</code> modules from CPAN.
</para>
<para>
もしそれが常に同じ書式である十分に標準的な文字列であれば、それを分割して、
その部分部分を標準の Time::Local モジュールの <code>timelocal</code> に渡せます。
さもなければ、CPAN にある <code>Date::Calc</code> モジュールと
<code>Date::Manip</code> モジュールを見るべきでしょう。
</para>
</sect2>
<sect2>
<title>How can I find the Julian Day?</title>
<para>
(ユリウス日を求めるには?)
</para>
<para>
(contributed by brian d foy and Dave Cross)
</para>
<para>
(brian d foy と Dave Cross によって寄贈されました)
</para>
<para>
You can use the <code>Time::JulianDay</code> module available on CPAN.  Ensure
that you really want to find a Julian day, though, as many people have
different ideas about Julian days.  See
<xlink uri='http://www.hermetic.ch/cal_stud/jdn.htm'>http://www.hermetic.ch/cal_stud/jdn.htm</xlink> for instance.
</para>
<para>
CPAN にある <code>Time::JulianDay</code> モジュールが使えます。
しかし、本当にユリウス日がほしいのか確認してください;
多くの人々がユリウス日に関して異なる考え方を持っています。
例としては、<xlink uri='http://www.hermetic.ch/cal_stud/jdn.htm'>http://www.hermetic.ch/cal_stud/jdn.htm</xlink> を参照してください。
</para>
<para>
You can also try the <code>DateTime</code> module, which can convert a date/time
to a Julian Day.
</para>
<para>
日付・時刻をユリウス日に変換できる、<code>DateTime</code> モジュールを試すことも
できます。
</para>
<verbatim><![CDATA[
$ perl -MDateTime -le'print DateTime->today->jd'
2453401.5
]]></verbatim>
<para>
Or the modified Julian Day
</para>
<para>
あるいは準ユリウス日にも変換できます:
</para>
<verbatim><![CDATA[
$ perl -MDateTime -le'print DateTime->today->mjd'
53401
]]></verbatim>
<para>
Or even the day of the year (which is what some people think of as a
Julian day)
</para>
<para>
あるいは年の何日目か(これがユリウス日だと考える人もいます)にも変換できます:
</para>
<verbatim><![CDATA[
$ perl -MDateTime -le'print DateTime->today->doy'
31
]]></verbatim>
</sect2>
<sect2>
<title>How do I find yesterday's date?</title>
<para>
(昨日の日付を得るには?)
</para>
<para>
(contributed by brian d foy)
</para>
<para>
(brian d foy によって寄贈されました)
</para>
<para>
Use one of the Date modules. The <code>DateTime</code> module makes it simple, and
give you the same time of day, only the day before.
</para>
<para>
Date モジュールの一つを使いましょう。
<code>DateTime</code> モジュールは単純で、前日の同じ時刻を返します。
</para>
<verbatim><![CDATA[
use DateTime;
]]></verbatim>
<verbatim><![CDATA[
my $yesterday = DateTime->now->subtract( days => 1 );
]]></verbatim>
<verbatim><![CDATA[
print "Yesterday was $yesterday\n";
]]></verbatim>
<para>
You can also use the <code>Date::Calc</code> module using its <code>Today_and_Now</code>
function.
</para>
<para>
<code>Date::Calc</code> モジュールの <code>Today_and_Now</code> 関数を使うこともできます。
</para>
<verbatim><![CDATA[
use Date::Calc qw( Today_and_Now Add_Delta_DHMS );
]]></verbatim>
<verbatim><![CDATA[
my @date_time = Add_Delta_DHMS( Today_and_Now(), -1, 0, 0, 0 );
]]></verbatim>
<verbatim><![CDATA[
print "@date_time\n";
]]></verbatim>
<para>
Most people try to use the time rather than the calendar to figure out
dates, but that assumes that days are twenty-four hours each.  For
most people, there are two days a year when they aren't: the switch to
and from summer time throws this off. Let the modules do the work.
</para>
<para>
ほとんどの人は日付を計算するのにカレンダーではなく時刻を使おうとしますが、
これは 1 日が 24 時間であることを仮定しています。
ほとんどの人々にとって、そうではない日が 2 日あります:
夏時間が始まる日と終わる日はこれを狂わせます。
この作業はモジュールにさせましょう。
</para>
</sect2>
<sect2>
<title>Does Perl have a Year 2000 problem? Is Perl Y2K compliant?</title>
<para>
(Perl には 2000 年問題があるのですか? Perl は 2000 年対応ですか?)
</para>
<para>
Short answer: No, Perl does not have a Year 2000 problem.  Yes, Perl is
Y2K compliant (whatever that means). The programmers you've hired to
use it, however, probably are not.
</para>
<para>
短い答: いいえ、Perl には 2000 年問題はありません。
はい、Perl は(どのような意味でも) 2000 年対応です。
ただし、あなたの雇っているプログラマがそうでないように
使っているなら 2000 年問題はあります。
</para>
<para>
Long answer: The question belies a true understanding of the issue.
Perl is just as Y2K compliant as your pencil--no more, and no less.
Can you use your pencil to write a non-Y2K-compliant memo?  Of course
you can.  Is that the pencil's fault?  Of course it isn't.
</para>
<para>
長い答: この質問は物事の理解を誤っています。
Perl はあなたの鉛筆と同じぐらいに Y2K 対応です。
それ以上でもそれ以下でもありません。
あなたの鉛筆を使って Y2K 対応でないメモを書けますか? もちろん書けます。
それは鉛筆のせいですか? もちろん違います。
</para>
<para>
The date and time functions supplied with Perl (gmtime and localtime)
supply adequate information to determine the year well beyond 2000
(2038 is when trouble strikes for 32-bit machines).  The year returned
by these functions when used in a list context is the year minus 1900.
For years between 1910 and 1999 this <emphasis>happens</emphasis> to be a 2-digit decimal
number. To avoid the year 2000 problem simply do not treat the year as
a 2-digit number.  It isn't.
</para>
<para>
Perl に組み込みの日付・時刻関数(gmtimeとlocaltime)は
2000 年を越えた年も区別するために必要な情報を提供しています
(32 ビットマシンをトラブルが直撃するのは2038年です)。
これらの関数がリストコンテキストで使われたときに返す年数は
実際の年から 1900 を引いた値です。1910 年から 1999 年は
このやり方では <strong>たまたま</strong> 二桁の数値となります。
2000 年問題を避けるには、年を二桁で扱わないようにします。
</para>
<para>
When gmtime() and localtime() are used in scalar context they return
a timestamp string that contains a fully-expanded year.  For example,
<code>$timestamp = gmtime(1005613200)</code> sets $timestamp to &quot;Tue Nov 13 01:00:00
2001&quot;.  There's no year 2000 problem here.
</para>
<para>
gmtime() や localtime() は、スカラコンテキストで呼び出された場合には
完全な年を含んでいるタイムスタンプ文字列を返します。
たとえば、<code>$timestamp = gmtime(1005613200)</code> は
$timestamp に &quot;Tue Nov 13 01:00:00 2001&quot; をセットします。
ここには 2000 年問題はありません。
</para>
<para>
That doesn't mean that Perl can't be used to create non-Y2K compliant
programs.  It can.  But so can your pencil.  It's the fault of the user,
not the language.  At the risk of inflaming the NRA: &quot;Perl doesn't
break Y2K, people do.&quot;  See <xlink uri='http://www.perl.org/about/y2k.html'>http://www.perl.org/about/y2k.html</xlink> for
a longer exposition.
</para>
<para>
このことは、Perl で 2000 年問題を起こすようなプログラムを作るのに
使えないということではありません。あなたの使う鉛筆も
そうであるように。つまり、言語にまつわるミスではなく、使う人の
間違いであるということです。
NRA を刺激するかもしれませんが、
「Perl は 2000 年問題を打ち破らない。人が打ち破るのだ。」ということです。
詳しい説明は <xlink uri='http://www.perl.org/about/y2k.html'>http://www.perl.org/about/y2k.html</xlink> を参照してください。
</para>
</sect2>
</sect1>
<sect1>
<title>Data: Strings</title>
<para>
(データ: 文字列)
</para>
<sect2>
<title>How do I validate input?</title>
<para>
(入力を検査するには?)
</para>
<para>
(contributed by brian d foy)
</para>
<para>
(brian d foy によって寄贈されました)
</para>
<para>
There are many ways to ensure that values are what you expect or
want to accept. Besides the specific examples that we cover in the
perlfaq, you can also look at the modules with &quot;Assert&quot; and &quot;Validate&quot;
in their names, along with other modules such as <code>Regexp::Common</code>.
</para>
<para>
値があなたの予測している、または受け入れたいものであることを保証するには
多くの方法があります。
perlfaq でカバーする特定の例の他に、名前に &quot;Assert&quot; や &quot;Validate&quot; がある
モジュールや、<code>Regexp::Common</code> のようなその他のモジュールを
見ることもできます。
</para>
<para>
Some modules have validation for particular types of input, such
as <code>Business::ISBN</code>, <code>Business::CreditCard</code>, <code>Email::Valid</code>,
and <code>Data::Validate::IP</code>.
</para>
<para>
<code>Business::ISBN</code>, <code>Business::CreditCard</code>, <code>Email::Valid</code>,
<code>Data::Validate::IP</code> のように、特定の種類の入力を検査するための
モジュールもあります。
</para>
</sect2>
<sect2>
<title>How do I unescape a string?</title>
<para>
(文字列のアンエスケープ (unescape)をするには?)
</para>
<para>
It depends just what you mean by &quot;escape&quot;.  URL escapes are dealt
with in <link xref='perlfaq9'>perlfaq9</link>.  Shell escapes with the backslash (<code>\</code>)
character are removed with
</para>
<para>
それはあなたのいう「エスケープ」がなんであるかによります。
URL のエスケープは <link xref='perlfaq9'>perlfaq9</link> で扱っています。
バックスラッシュによるシェルエスケープは以下のようにして取り除きます:
</para>
<verbatim><![CDATA[
s/\\(.)/$1/g;
]]></verbatim>
<para>
This won't expand <code>&quot;\n&quot;</code> or <code>&quot;\t&quot;</code> or any other special escapes.
</para>
<para>
これは <code>\n</code> だとか <code>\t</code>、あるいはその他の特殊なエスケープを展開しません。
</para>
</sect2>
<sect2>
<title>How do I remove consecutive pairs of characters?</title>
<para>
(キャラクタの連続した組を取り除くには?)
</para>
<para>
(contributed by brian d foy)
</para>
<para>
(brian d foy によって寄贈されました)
</para>
<para>
You can use the substitution operator to find pairs of characters (or
runs of characters) and replace them with a single instance. In this
substitution, we find a character in <code>(.)</code>. The memory parentheses
store the matched character in the back-reference <code>\1</code> and we use
that to require that the same thing immediately follow it. We replace
that part of the string with the character in <code>$1</code>.
</para>
<para>
文字の組(または文字の並び)を探して、それを一つの実体に置き換えるには
置換演算子が使えます。
この置換で、<code>(.)</code> で一文字が見付かります。
記憶用のかっこはマッチングした文字を後方参照 <code>\1</code> に保管し、
同じ文字を直後に要求するために使います。
文字列の一部を <code>$1</code> にある文字で置き換えます。
</para>
<verbatim><![CDATA[
s/(.)\1/$1/g;
]]></verbatim>
<para>
We can also use the transliteration operator, <code>tr///</code>. In this
example, the search list side of our <code>tr///</code> contains nothing, but
the <code>c</code> option complements that so it contains everything. The
replacement list also contains nothing, so the transliteration is
almost a no-op since it won't do any replacements (or more exactly,
replace the character with itself). However, the <code>s</code> option squashes
duplicated and consecutive characters in the string so a character
does not show up next to itself
</para>
<para>
文字変換演算子 <code>tr///</code> も使えます。
この例では、<code>tr///</code> の検索リスト側は何も入っていませんが、<code>c</code> オプションが
ついているので全てが含まれます。
置き換えリスト側にも何も入っていないので、文字変換はほとんど何もしません
(より厳密には、文字はその文字自身に置き換えられます)。
しかし、<code>s</code> オプションは文字列中の重複していて連続した文字を 1 文字に
短縮するので、次に同じ文字がある文字は表示されません:
</para>
<verbatim><![CDATA[
my $str = 'Haarlem';   # in the Netherlands
$str =~ tr///cs;       # Now Harlem, like in New York
]]></verbatim>
</sect2>
<sect2>
<title>How do I expand function calls in a string?</title>
<para>
(文字列中にある関数呼び出しを展開するには?)
</para>
<para>
(contributed by brian d foy)
</para>
<para>
(brian d foy によって寄贈されました)
</para>
<para>
This is documented in <link xref='perlref'>perlref</link>, and although it's not the easiest
thing to read, it does work. In each of these examples, we call the
function inside the braces used to dereference a reference. If we
have more than one return value, we can construct and dereference an
anonymous array. In this case, we call the function in list context.
</para>
<para>
これは <link xref='perlref'>perlref</link> に文書化されていて、もっとも読みやすいものでは
ありませんが、動きます。
これらの例のそれぞれにおいて、大かっこの内側の関数はリファレンスを
デリファレンスするために呼び出します。
もし複数の返り値がある場合、無名配列を構築して、デリファレンスします。
この場合、関数をリストコンテキストで呼び出します。
</para>
<verbatim><![CDATA[
print "The time values are @{ [localtime] }.\n";
]]></verbatim>
<para>
If we want to call the function in scalar context, we have to do a bit
more work. We can really have any code we like inside the braces, so
we simply have to end with the scalar reference, although how you do
that is up to you, and you can use code inside the braces. Note that
the use of parens creates a list context, so we need <code>scalar</code> to
force the scalar context on the function:
</para>
<para>
スカラコンテキストで関数を呼び出したい場合、もう少し作業が必要です。
実際に置きたいどんなコードでも中かっこの中に置けるので、
(それをどのようにするかはあなた次第で、中かっこのなかのコードを使えますが)
単にスカラリファレンスで終了する必要があります。
かっこはリストコンテキストを作成するので、関数内でスカラコンテキストを
強制するために <code>scalar</code> が必要であることに注意してください:
</para>
<verbatim><![CDATA[
print "The time is ${\(scalar localtime)}.\n"
]]></verbatim>
<verbatim><![CDATA[
print "The time is ${ my $x = localtime; \$x }.\n";
]]></verbatim>
<para>
If your function already returns a reference, you don't need to create
the reference yourself.
</para>
<para>
関数がすでにリファレンスを返す場合、自分でリファレンスを作る必要は
ありません。
</para>
<verbatim><![CDATA[
sub timestamp { my $t = localtime; \$t }
]]></verbatim>
<verbatim><![CDATA[
print "The time is ${ timestamp() }.\n";
]]></verbatim>
<para>
The <code>Interpolation</code> module can also do a lot of magic for you. You can
specify a variable name, in this case <code>E</code>, to set up a tied hash that
does the interpolation for you. It has several other methods to do this
as well.
</para>
<para>
<code>Interpolation</code> モジュールもまたあなたのために多くの魔法を使います。
展開を行う tie されたハッシュを設定するための変数名(この場合は <code>E</code>)を
指定できます。
同じようにこれを行うその他のいくつかのメソッドを持っています。
</para>
<verbatim><![CDATA[
use Interpolation E => 'eval';
print "The time values are $E{localtime()}.\n";
]]></verbatim>
<para>
In most cases, it is probably easier to simply use string concatenation,
which also forces scalar context.
</para>
<para>
ほとんどの場合、文字列連結を使ってスカラコンテキストに強制するほうが
おそらくより簡単です。
</para>
<verbatim><![CDATA[
print "The time is " . localtime() . ".\n";
]]></verbatim>
</sect2>
<sect2>
<title>How do I find matching/nesting anything?</title>
<para>
(何かがマッチしている/ネストしているということを検出するには?)
</para>
<para>
This isn't something that can be done in one regular expression, no
matter how complicated.  To find something between two single
characters, a pattern like <code>/x([^x]*)x/</code> will get the intervening
bits in $1. For multiple ones, then something more like
<code>/alpha(.*?)omega/</code> would be needed. But none of these deals with
nested patterns.  For balanced expressions using <code>(</code>, <code>{</code>, <code>[</code> or
<code>&lt;</code> as delimiters, use the CPAN module Regexp::Common, or see
<link xref='perlre#(??{ code >)'}perlre/(??{ code })</link>.  For other cases, you'll have to write a
parser.
</para>
<para>
これは一つの正規表現で解決できないほどの複雑な問題なのです。
単一のキャラクター二つに囲まれた何かを見つけだすには、 
<code>/x([^x]*)x/</code> といったパターンを使えば $1 に検査の結果が得られるでしょう。
複数キャラクターに囲まれたものの場合は、
<code>/alpha(.*?)omega/</code> のようなパターンが必要となるでしょう。
しかし、ネストしたパターンを扱うようなものはありませんし、できません。
<code>(</code>, <code>{</code>, <code>[</code>, <code>&lt;</code> のいずれかのバランス表現をデリミタとして
使っている場合、CPAN にある Regexp::Common モジュールを使うか、
<link xref='perlre#(??{ code >)'}perlre/(??{ code })</link> を参照してください。
その他の場合では、パーサーを書く必要があります。
</para>
<para>
If you are serious about writing a parser, there are a number of
modules or oddities that will make your life a lot easier.  There are
the CPAN modules <code>Parse::RecDescent</code>, <code>Parse::Yapp</code>, and
<code>Text::Balanced</code>; and the <code>byacc</code> program. Starting from perl 5.8
the <code>Text::Balanced</code> is part of the standard distribution.
</para>
<para>
もしまじめにパーザを作ろうと考えているのなら、
それを手助けしてくれるようなモジュールやその他のプログラムがあります。
CPAN には <code>Parse::RecDescent</code>, <code>Parse::Yapp</code>, <code>Text::Balanced</code>
がありますし、<code>byacc</code> プログラムもあります。
perl 5.8 から、<code>Text::Balanced</code> は標準配布の一部になりました。
</para>
<para>
One simple destructive, inside-out approach that you might try is to
pull out the smallest nesting parts one at a time:
</para>
<para>
単純で破壊的な inside-out アプローチもあります。
これは以下のようにして一度に最小のネスト部分を取り出そうというものです。
</para>
<verbatim><![CDATA[
while (s/BEGIN((?:(?!BEGIN)(?!END).)*)END//gs) {
	# do something with $1
	}
]]></verbatim>
<para>
A more complicated and sneaky approach is to make Perl's regular
expression engine do it for you.  This is courtesy Dean Inada, and
rather has the nature of an Obfuscated Perl Contest entry, but it
really does work:
</para>
<para>
より複雑で巧妙なやり方に Perl の正規表現エンジンを使うというものがあります。
これは Dean Inada によるもので Obfuscated Perl コンテストに
エントリされるような代物ですが、正しく働きます:
</para>
<verbatim><![CDATA[
# $_ contains the string to parse
# BEGIN and END are the opening and closing markers for the
# nested text.
]]></verbatim>
<verbatim><![CDATA[
# $_ には解析対象の文字列があります
# BEGINとENDはネストしたテキストの開始と終了とを行います。
]]></verbatim>
<verbatim><![CDATA[
@( = ('(','');
@) = (')','');
($re=$_)=~s/((BEGIN)|(END)|.)/$)[!$3]\Q$1\E$([!$2]/gs;
@$ = (eval{/$re/},$@!~/unmatched/i);
print join("\n",@$[0..$#$]) if( $$[-1] );
]]></verbatim>
</sect2>
<sect2>
<title>How do I reverse a string?</title>
<para>
(文字列をひっくり返すには?)
</para>
<para>
Use <code>reverse()</code> in scalar context, as documented in
<link xref='perlfunc#reverse'>perlfunc/reverse</link>.
</para>
<para>
<link xref='perlfunc#reverse'>perlfunc/reverse</link> で説明されているように、スカラコンテキストで
<code>reverse()</code> を使います。
</para>
<verbatim><![CDATA[
$reversed = reverse $string;
]]></verbatim>
</sect2>
<sect2>
<title>How do I expand tabs in a string?</title>
<para>
(文字列中にあるタブを展開するには?)
</para>
<para>
You can do it yourself:
</para>
<para>
以下のようにしてできます:
</para>
<verbatim><![CDATA[
1 while $string =~ s/\t+/' ' x (length($&) * 8 - length($`) % 8)/e;
]]></verbatim>
<para>
Or you can just use the <code>Text::Tabs</code> module (part of the standard Perl
distribution).
</para>
<para>
あるいは、ただ単に <code>Text::Tabs</code> モジュール(標準 Perl 配布キットの一部です)を
使ってもできます。
</para>
<verbatim><![CDATA[
use Text::Tabs;
@expanded_lines = expand(@lines_with_tabs);
]]></verbatim>
</sect2>
<sect2>
<title>How do I reformat a paragraph?</title>
<para>
(段落を整形するには?)
</para>
<para>
Use <code>Text::Wrap</code> (part of the standard Perl distribution):
</para>
<para>
<code>Text::Wrap</code> (標準 Perl 配布キットの一部です)を使います。
</para>
<verbatim><![CDATA[
use Text::Wrap;
print wrap("\t", '  ', @paragraphs);
]]></verbatim>
<para>
The paragraphs you give to <code>Text::Wrap</code> should not contain embedded
newlines.  <code>Text::Wrap</code> doesn't justify the lines (flush-right).
</para>
<para>
<code>Text::Wrap</code> に与える段落には埋め込みの改行があってはいけません。
<code>Text::Wrap</code> は行を均等割り付けしません(左寄せします)。
</para>
<para>
Or use the CPAN module <code>Text::Autoformat</code>.  Formatting files can be
easily done by making a shell alias, like so:
</para>
<para>
または CPAN の <code>Text::Autoformat</code> モジュールを使ってください。
ファイルの整形は以下のようにシェルエイリアスを作ることによって
簡単に実現できます:
</para>
<verbatim><![CDATA[
alias fmt="perl -i -MText::Autoformat -n0777 \
	-e 'print autoformat $_, {all=>1}' $*"
]]></verbatim>
<para>
See the documentation for <code>Text::Autoformat</code> to appreciate its many
capabilities.
</para>
<para>
その多くの能力を評価するために、<code>Text::Autoformat</code> の文書を
参照してください。
</para>
</sect2>
<sect2>
<title>How can I access or change N characters of a string?</title>
<para>
(文字列の最初の N 文字にアクセスしたり、それを変更するには?)
</para>
<para>
You can access the first characters of a string with substr().
To get the first character, for example, start at position 0
and grab the string of length 1.
</para>
<para>
文字列の先頭の文字へは substr() でアクセスできます。
例えば、最初の文字を得るには、位置 0 から始めて、長さ 1 の文字列を
取得します。
</para>
<verbatim><![CDATA[
$string = "Just another Perl Hacker";
$first_char = substr( $string, 0, 1 );  #  'J'
]]></verbatim>
<para>
To change part of a string, you can use the optional fourth
argument which is the replacement string.
</para>
<para>
文字列の一部を変換するために、省略可能な 4 番目の引数として置き換える
文字列を指定できます。
</para>
<verbatim><![CDATA[
substr( $string, 13, 4, "Perl 5.8.0" );
]]></verbatim>
<para>
You can also use substr() as an lvalue.
</para>
<para>
substr() を左辺値として使うこともできます。
</para>
<verbatim><![CDATA[
substr( $string, 13, 4 ) =  "Perl 5.8.0";
]]></verbatim>
</sect2>
<sect2>
<title>How do I change the Nth occurrence of something?</title>
<para>
(何かの N 番目のものを変更するには?)
</para>
<para>
You have to keep track of N yourself.  For example, let's say you want
to change the fifth occurrence of <code>&quot;whoever&quot;</code> or <code>&quot;whomever&quot;</code> into
<code>&quot;whosoever&quot;</code> or <code>&quot;whomsoever&quot;</code>, case insensitively.  These
all assume that $_ contains the string to be altered.
</para>
<para>
自分で N 番目の記録を取る必要があります。
例えば、(大小文字の違いを無視して) 5 番目に現れた
<code>&quot;whoever&quot;</code> か <code>&quot;whomever&quot;</code> を <code>&quot;whosoever&quot;</code> か
<code>&quot;whomsoever&quot;</code> に変更したいと考えているとしましょう。
以下は全て $_ に変更したい文字列が入っているものとします。
</para>
<verbatim><![CDATA[
$count = 0;
s{((whom?)ever)}{
++$count == 5       # is it the 5th?
    ? "${2}soever"  # yes, swap
    : $1            # renege and leave it there
	}ige;
]]></verbatim>
<para>
In the more general case, you can use the <code>/g</code> modifier in a <code>while</code>
loop, keeping count of matches.
</para>
<para>
もっと一般的なケースでは、<code>while</code> ループの中で
<code>/g</code> 修飾子を使ってマッチの数を数えることもできます。
</para>
<verbatim><![CDATA[
$WANT = 3;
$count = 0;
$_ = "One fish two fish red fish blue fish";
while (/(\w+)\s+fish\b/gi) {
	if (++$count == $WANT) {
		print "The third fish is a $1 one.\n";
		}
	}
]]></verbatim>
<para>
That prints out: <code>&quot;The third fish is a red one.&quot;</code>  You can also use a
repetition count and repeated pattern like this:
</para>
<para>
これは <code>&quot;The third fish is a red one.&quot;</code> のように出力します。
以下のようにパターンの繰り返し回数を指定するやり方もあります:
</para>
<verbatim><![CDATA[
/(?:\w+\s+fish\s+){2}(\w+)\s+fish/i;
]]></verbatim>
</sect2>
<sect2>
<title>How can I count the number of occurrences of a substring within a string?</title>
<para>
(ある文字列の中に存在する部分文字列が何個あるのかを数えるには?)
</para>
<para>
There are a number of ways, with varying efficiency.  If you want a
count of a certain single character (X) within a string, you can use the
<code>tr///</code> function like so:
</para>
<para>
様々な効率を持った、いろいろなやり方があります。
文字列中に存在しているある単一キャラクター (X) の数を数えたいのであれば、
<code>tr///</code> 関数を使って次のようにできます:
</para>
<verbatim><![CDATA[
$string = "ThisXlineXhasXsomeXx'sXinXit";
$count = ($string =~ tr/X//);
print "There are $count X characters in the string";
]]></verbatim>
<para>
This is fine if you are just looking for a single character.  However,
if you are trying to count multiple character substrings within a
larger string, <code>tr///</code> won't work.  What you can do is wrap a while()
loop around a global pattern match.  For example, let's count negative
integers:
</para>
<para>
これは単一キャラクターを対象にするのであればちょうどいいものですが、
大きな文字列中の、複数キャラクターから構成される部分文字列の数を
数えようとしても、<code>tr///</code> はうまく動作しません。
ここで可能なのは、グローバルなパターンマッチを while() で囲んでしまうという
ものです。たとえば、負の数を数えるのならこうします:
</para>
<verbatim><![CDATA[
$string = "-9 55 48 -2 23 -76 4 14 -44";
while ($string =~ /-\d+/g) { $count++ }
print "There are $count negative numbers in the string";
]]></verbatim>
<para>
Another version uses a global match in list context, then assigns the
result to a scalar, producing a count of the number of matches.
</para>
<para>
もう一つのバージョンでは、リストコンテキストでグローバルマッチングを
使って、その結果をスカラに代入することで、マッチングした数を数えます。
</para>
<verbatim><![CDATA[
$count = () = $string =~ /-\d+/g;
]]></verbatim>
</sect2>
<sect2>
<title>How do I capitalize all the words on one line?</title>
<para>
(一行にあるすべての単語をキャピタライズするには?)
</para>
<para>
To make the first letter of each word upper case:
</para>
<para>
各単語の最初の文字を大文字にするにはこうします:
</para>
<verbatim><![CDATA[
$line =~ s/\b(\w)/\U$1/g;
]]></verbatim>
<para>
This has the strange effect of turning &quot;<code>don't do it</code>&quot; into &quot;<code>Don'T
Do It</code>&quot;.  Sometimes you might want this.  Other times you might need a
more thorough solution (Suggested by brian d foy):
</para>
<para>
これには、&quot;<code>don't do it</code>&quot; を &quot;<code>Don'T Do It</code>&quot; にしてしまうような
妙な効果があります。
あなたがしたいのはこれでいいのかもしれません。
そうでないときには、以下のようにする必要があります
(Brian d Foy の提案によります):
</para>
<verbatim><![CDATA[
$string =~ s/ (
			 (^\w)    #at the beginning of the line
			   |      # or
			 (\s\w)   #preceded by whitespace
			   )
			/\U$1/xg;
]]></verbatim>
<verbatim><![CDATA[
$string =~ s/([\w']+)/\u\L$1/g;
]]></verbatim>
<para>
To make the whole line upper case:
</para>
<para>
行全体を大文字にするにはこうします:
</para>
<verbatim><![CDATA[
$line = uc($line);
]]></verbatim>
<para>
To force each word to be lower case, with the first letter upper case:
</para>
<para>
全ての語を小文字にし、それぞれの語の最初の文字を大文字にするには
こうします:
</para>
<verbatim><![CDATA[
$line =~ s/(\w+)/\u\L$1/g;
]]></verbatim>
<para>
You can (and probably should) enable locale awareness of those
characters by placing a <code>use locale</code> pragma in your program.
See <link xref='perllocale'>perllocale</link> for endless details on locales.
</para>
<para>
プログラムの中に <code>use locale</code> を置くことによって、
これらのキャラクターがロカールを意識するようにできます
(また、そうすべきです)。
ロカールに関する詳細は <link xref='perllocale'>perllocale</link> を参照してください。
</para>
<para>
This is sometimes referred to as putting something into &quot;title
case&quot;, but that's not quite accurate.  Consider the proper
capitalization of the movie <emphasis>Dr. Strangelove or: How I Learned to
Stop Worrying and Love the Bomb</emphasis>, for example.
</para>
<para>
これは“title case”として扱われることがありますが、
それは正確なものではありません。
例えば映画のタイトルである
<emphasis>Dr. Strangelove or: How I Learned to Stop Worrying and Love the Bomb</emphasis>
(邦題「博士の異常な愛情 または私は如何にして心配するのを止めて
水爆を愛するようになったか」)
を考えてみましょう。
</para>
<para>
Damian Conway's <link xref='Text::Autoformat'>Text::Autoformat</link> module provides some smart
case transformations:
</para>
<para>
Damian Conway による <link xref='Text::Autoformat'>Text::Autoformat</link> モジュールは、いくつかの
賢い大文字小文字変換を提供します:
</para>
<verbatim><![CDATA[
use Text::Autoformat;
my $x = "Dr. Strangelove or: How I Learned to Stop ".
  "Worrying and Love the Bomb";
]]></verbatim>
<verbatim><![CDATA[
print $x, "\n";
for my $style (qw( sentence title highlight )) {
	print autoformat($x, { case => $style }), "\n";
	}
]]></verbatim>
</sect2>
<sect2>
<title>How can I split a [character] delimited string except when inside [character]?</title>
<para>
((とある文字)の内側にある時を除き、(とある文字)で終端されている文字列を分割するには?)
</para>
<para>
Several modules can handle this sort of parsing--<code>Text::Balanced</code>,
<code>Text::CSV</code>, <code>Text::CSV_XS</code>, and <code>Text::ParseWords</code>, among others.
</para>
<para>
いくつかのモジュールがこのようなパースを扱います-- <code>Text::Balanced</code>,
<code>Text::CSV</code>, <code>Text::CSV_XS</code>, <code>Text::ParseWords</code> などです。
</para>
<para>
Take the example case of trying to split a string that is
comma-separated into its different fields. You can't use <code>split(/,/)</code>
because you shouldn't split if the comma is inside quotes.  For
example, take a data line like this:
</para>
<para>
カンマで分割された文字列を別々のフィールドに置くような例を
考えてみましょう。
ここで <code>split(/,/)</code> を使うことはできません。
なぜなら、クォートの内側にあるカンマで分割すべきではないからです。
例えば以下のようなデータを考えてみましょう。
</para>
<verbatim><![CDATA[
SAR001,"","Cimetrix, Inc","Bob Smith","CAM",N,8,1,0,7,"Error, Core Dumped"
]]></verbatim>
<para>
Due to the restriction of the quotes, this is a fairly complex
problem.  Thankfully, we have Jeffrey Friedl, author of
<emphasis>Mastering Regular Expressions</emphasis>, to handle these for us.  He
suggests (assuming your string is contained in <code>$text</code>):
</para>
<para>
クォートの制約のためにこれは実に複雑な問題です。
ありがたいことに、私たちには <emphasis>Mastering Regular Expressions</emphasis> の著者でもあり、
この問題を私たちのために扱ってくれる Jeffrey Friedl がいます。
彼の提案はこうです(文字列が <code>$text</code> にあると仮定しています):
</para>
<verbatim><![CDATA[
@new = ();
push(@new, $+) while $text =~ m{
		 "([^\"\\]*(?:\\.[^\"\\]*)*)",?  # groups the phrase inside the quotes
		| ([^,]+),?
		| ,
		}gx;
push(@new, undef) if substr($text,-1,1) eq ',';
]]></verbatim>
<para>
If you want to represent quotation marks inside a
quotation-mark-delimited field, escape them with backslashes (eg,
<code>&quot;like \&quot;this\&quot;&quot;</code>.
</para>
<para>
クォーテーションマークで終端されたフィールドの中で
クォーテーションマークを表現したいのならば、
それをバックスラッシュで(<code>&quot;like \&quot;this\&quot;&quot;</code> のように)エスケープしてください。
</para>
<para>
Alternatively, the <code>Text::ParseWords</code> module (part of the standard
Perl distribution) lets you say:
</para>
<para>
あるいは、<code>Text::PaserWords</code> モジュール(標準 Perl 配布の一部です)を
使ってこうします:
</para>
<verbatim><![CDATA[
use Text::ParseWords;
@new = quotewords(",", 0, $text);
]]></verbatim>
</sect2>
<sect2>
<title>How do I strip blank space from the beginning/end of a string?</title>
<para>
(文字列の先頭や末尾にある空白を剥ぎ取るには?)
</para>
<para>
(contributed by brian d foy)
</para>
<para>
(brian d foy によって寄贈されました)
</para>
<para>
A substitution can do this for you. For a single line, you want to
replace all the leading or trailing whitespace with nothing. You
can do that with a pair of substitutions.
</para>
<para>
置換を使うことで行えます。
1 行では、先頭か末尾のどちらかの空白全てを削除します。
2 つの置換でこれが行えます。
</para>
<verbatim><![CDATA[
s/^\s+//;
s/\s+$//;
]]></verbatim>
<para>
You can also write that as a single substitution, although it turns
out the combined statement is slower than the separate ones. That
might not matter to you, though.
</para>
<para>
これを 1 回の置換で書くこともできますが、組み合わせた文は分かれている
文よりも遅くなります。
しかし、それはあなたには問題がないかもしれません。
</para>
<verbatim><![CDATA[
s/^\s+|\s+$//g;
]]></verbatim>
<para>
In this regular expression, the alternation matches either at the
beginning or the end of the string since the anchors have a lower
precedence than the alternation. With the <code>/g</code> flag, the substitution
makes all possible matches, so it gets both. Remember, the trailing
newline matches the <code>\s+</code>, and  the <code>$</code> anchor can match to the
physical end of the string, so the newline disappears too. Just add
the newline to the output, which has the added benefit of preserving
&quot;blank&quot; (consisting entirely of whitespace) lines which the <code>^\s+</code>
would remove all by itself.
</para>
<para>
この正規表現において、アンカーは the alternation より低い優先順位を
持つので、the alternation は文字列の先頭か末尾にマッチングします。
<code>/g</code> フラグが付いていることにより、可能な全てのマッチングについて置換が
行われるので、先頭と末尾の両方で行われます。
引き続く改行は <code>\s+</code> にマッチングし、<code>$</code> アンカーは文字列の物理的な
末尾にマッチングするので、改行も消えることを忘れないでください。
単に出力に改行を追加することで、<code>^\s+</code> がすべて削除してしまう「空の」
(空白だけからなる)行を保存する利点が追加されます。
</para>
<verbatim><![CDATA[
while( <> )
	{
	s/^\s+|\s+$//g;
	print "$_\n";
	}
]]></verbatim>
<para>
For a multi-line string, you can apply the regular expression
to each logical line in the string by adding the <code>/m</code> flag (for
&quot;multi-line&quot;). With the <code>/m</code> flag, the <code>$</code> matches <emphasis>before</emphasis> an
embedded newline, so it doesn't remove it. It still removes the
newline at the end of the string.
</para>
<para>
複数行の文字列に対しては、<code>/m</code> (&quot;multi-line&quot;) フラグを追加することにより、
文字列中の論理行毎に正規表現を適用できます。
<code>/m</code> フラグをつけると、<code>$</code> 組み込まれた改行の <emphasis>前に</emphasis> マッチングするので、
これを取り除けません。
文字列の末尾の改行は取り除けます。
</para>
<verbatim><![CDATA[
$string =~ s/^\s+|\s+$//gm;
]]></verbatim>
<para>
Remember that lines consisting entirely of whitespace will disappear,
since the first part of the alternation can match the entire string
and replace it with nothing. If need to keep embedded blank lines,
you have to do a little more work. Instead of matching any whitespace
(since that includes a newline), just match the other whitespace.
</para>
<para>
空白だけからなる文字列は、置換の最初の部分が文字列全体にマッチングして、
それを空文字列に置き換えてしまうので、消えてしまうことに注意してください。
もし組み込まれている空行を保存したいなら、さらにもう少し作業をする必要が
あります。
全ての空白(改行を含みます)にマッチングさせる代わりに、単にその他の
空白にマッチングさせます。
</para>
<verbatim><![CDATA[
$string =~ s/^[\t\f ]+|[\t\f ]+$//mg;
]]></verbatim>
</sect2>
<sect2>
<title>How do I pad a string with blanks or pad a number with zeroes?</title>
<para>
(文字列に空白をパッディングしたり、数値にゼロをパッディングしたりするには?)
</para>
<para>
In the following examples, <code>$pad_len</code> is the length to which you wish
to pad the string, <code>$text</code> or <code>$num</code> contains the string to be padded,
and <code>$pad_char</code> contains the padding character. You can use a single
character string constant instead of the <code>$pad_char</code> variable if you
know what it is in advance. And in the same way you can use an integer in
place of <code>$pad_len</code> if you know the pad length in advance.
</para>
<para>
以下に挙げる例で、<code>$pad_len</code> はパッディングしたい文字列の長さです。
<code>$text</code> や <code>$num</code> は文字列にパッディングの対象となる内容を保持していて、
<code>$pad_char</code> がパッディングに使いたいキャラクターを保持しています。
やっていることがわかっているのなら、<code>$pad_char</code> という変数の代わりに一
文字のキャラクター文字列を使うこともできます。
そして同様に、パッディングしたい長さが予め分かっているなら、
<code>$pad_len</code> に整数値を指定することも出来ます。
</para>
<para>
The simplest method uses the <code>sprintf</code> function. It can pad on the left
or right with blanks and on the left with zeroes and it will not
truncate the result. The <code>pack</code> function can only pad strings on the
right with blanks and it will truncate the result to a maximum length of
<code>$pad_len</code>.
</para>
<para>
最も単純なやり方は <code>sprintf</code> 関数を使うというものです。
この関数は文字列の左や右にパッディングを行ったり、0 を左に置いたりする
ことができます。
<code>pack</code> 関数は文字列の右側に空白でパッディングすることと、
結果の最大長を <code>$pad_len</code> に切り詰めることだけができます。
</para>
<verbatim><![CDATA[
# Left padding a string with blanks (no truncation):
$padded = sprintf("%${pad_len}s", $text);
$padded = sprintf("%*s", $pad_len, $text);  # same thing
]]></verbatim>
<verbatim><![CDATA[
# Right padding a string with blanks (no truncation):
$padded = sprintf("%-${pad_len}s", $text);
$padded = sprintf("%-*s", $pad_len, $text); # same thing
]]></verbatim>
<verbatim><![CDATA[
# Left padding a number with 0 (no truncation):
$padded = sprintf("%0${pad_len}d", $num);
$padded = sprintf("%0*d", $pad_len, $num); # same thing
]]></verbatim>
<verbatim><![CDATA[
# Right padding a string with blanks using pack (will truncate):
$padded = pack("A$pad_len",$text);
]]></verbatim>
<para>
If you need to pad with a character other than blank or zero you can use
one of the following methods.  They all generate a pad string with the
<code>x</code> operator and combine that with <code>$text</code>. These methods do
not truncate <code>$text</code>.
</para>
<para>
空白やゼロ以外のキャラクターでパッディングを行いたいのであれば、
以下に挙げるやり方を使うことができます。これらは全て
パッディング文字列を <code>x</code> 修飾子で生成して <code>$text</code> と結合します。
これらのメソッドは <code>$text</code> を切り詰めません。
</para>
<para>
Left and right padding with any character, creating a new string:
</para>
<para>
任意のキャラクターによる左詰めと右詰めを行い、新しい文字列を作ります:
</para>
<verbatim><![CDATA[
$padded = $pad_char x ( $pad_len - length( $text ) ) . $text;
$padded = $text . $pad_char x ( $pad_len - length( $text ) );
]]></verbatim>
<para>
Left and right padding with any character, modifying <code>$text</code> directly:
</para>
<para>
任意のキャラクターによる左詰めと右詰めを行い、<code>$text</code> を直接変更します:
</para>
<verbatim><![CDATA[
substr( $text, 0, 0 ) = $pad_char x ( $pad_len - length( $text ) );
$text .= $pad_char x ( $pad_len - length( $text ) );
]]></verbatim>
</sect2>
<sect2>
<title>How do I extract selected columns from a string?</title>
<para>
(文字列から選択されたカラムを取り出すには?)
</para>
<para>
(contributed by brian d foy)
</para>
<para>
(brian d foy によって寄贈されました)
</para>
<para>
If you know where the columns that contain the data, you can
use <code>substr</code> to extract a single column.
</para>
<para>
データが含まれている桁が分かっているなら、単一の桁を展開するために
<code>substr</code> が使えます。
</para>
<verbatim><![CDATA[
my $column = substr( $line, $start_column, $length );
]]></verbatim>
<para>
You can use <code>split</code> if the columns are separated by whitespace or
some other delimiter, as long as whitespace or the delimiter cannot
appear as part of the data.
</para>
<para>
桁が空白やその他のデリミタで分けられていて、データの一部としては
空白やデリミタが現れないなら、<code>split</code> が使えます。
</para>
<verbatim><![CDATA[
my $line    = ' fred barney   betty   ';
my @columns = split /\s+/, $line;
	# ( '', 'fred', 'barney', 'betty' );
]]></verbatim>
<verbatim><![CDATA[
my $line    = 'fred||barney||betty';
my @columns = split /\|/, $line;
	# ( 'fred', '', 'barney', '', 'betty' );
]]></verbatim>
<para>
If you want to work with comma-separated values, don't do this since
that format is a bit more complicated. Use one of the modules that
handle that fornat, such as <code>Text::CSV</code>, <code>Text::CSV_XS</code>, or
<code>Text::CSV_PP</code>.
</para>
<para>
カンマ区切りの値(CSV)を扱いたい場合は、フォーマットが少し複雑なので
これはしないで下さい。
<code>Text::CSV</code>, <code>Text::CSV_XS</code>, <code>Text::CSV_PP</code> のような、この
フォーマットを扱うためのモジュールの一つを使ってください。
</para>
<para>
If you want to break apart an entire line of fixed columns, you can use
<code>unpack</code> with the A (ASCII) format. by using a number after the format
specifier, you can denote the column width. See the <code>pack</code> and <code>unpack</code>
entries in <link xref='perlfunc'>perlfunc</link> for more details.
</para>
<para>
固定桁の行全体を分解したいなら、<code>unpack</code> の A (ASCII) フォーマットが
使えます。
フォーマット指定子の後に数値をつけることで、桁数を指定できます。
更なる詳細については <link xref='perlfunc'>perlfunc</link> の <code>pack</code> と <code>unpack</code> の項目を
参照してください。
</para>
<verbatim><![CDATA[
my @fields = unpack( $line, "A8 A8 A8 A16 A4" );
]]></verbatim>
<para>
Note that spaces in the format argument to <code>unpack</code> do not denote literal
spaces. If you have space separated data, you may want <code>split</code> instead.
</para>
<para>
<code>unpack</code> のフォーマット引数での空白はリテラルな空白を意味しないことに
注意してください。
もし空白で区切られたデータがあるなら、代わりに <code>split</code> を使ったほうが
いいかもしれません。
</para>
</sect2>
<sect2>
<title>How do I find the soundex value of a string?</title>
<para>
(文字列の soundex 値を見つけるには?)
</para>
<para>
(contributed by brian d foy)
</para>
<para>
(brian d foy によって寄贈されました)
</para>
<para>
You can use the Text::Soundex module. If you want to do fuzzy or close
matching, you might also try the <code>String::Approx</code>, and
<code>Text::Metaphone</code>, and <code>Text::DoubleMetaphone</code> modules.
</para>
<para>
Text::Soundex モジュールが使えます。
あいまいマッチングや近傍マッチングを行いたいなら、
<code>String::Approx</code>, <code>Text::Metaphone</code>, <code>Text::DoubleMetaphone</code> といった
モジュールを試すのも良いでしょう。
</para>
</sect2>
<sect2>
<title>How can I expand variables in text strings?</title>
<para>
(テキスト文字列の中にある変数を展開するには?)
</para>
<para>
(contributed by brian d foy)
</para>
<para>
(brian d foy によって寄贈されました)
</para>
<para>
If you can avoid it, don't, or if you can use a templating system,
such as <code>Text::Template</code> or <code>Template</code> Toolkit, do that instead. You
might even be able to get the job done with <code>sprintf</code> or <code>printf</code>:
</para>
<para>
もし避けることが可能なら、してはいけません;
あるいは、<code>Text::Template</code> や <code>Template</code> ツールキットのような
テンプレートシステムが使えるなら、これらを代わりに使ってください。
<code>sprintf</code> や <code>printf</code> を使って作業をこなすことすらできます:
</para>
<verbatim><![CDATA[
my $string = sprintf 'Say hello to %s and %s', $foo, $bar;
]]></verbatim>
<para>
However, for the one-off simple case where I don't want to pull out a
full templating system, I'll use a string that has two Perl scalar
variables in it. In this example, I want to expand <code>$foo</code> and <code>$bar</code>
to their variable's values:
</para>
<para>
しかし、完全なテンプレートシステムを引っ張り出したくないような一度限りの
簡単な場合には、内部に二つの Perl スカラ変数を持つ文字列を使います。
この例では、<code>$foo</code> と <code>$bar</code> をその変数の値に展開したいとします:
</para>
<verbatim><![CDATA[
my $foo = 'Fred';
my $bar = 'Barney';
$string = 'Say hello to $foo and $bar';
]]></verbatim>
<para>
One way I can do this involves the substitution operator and a double
<code>/e</code> flag.  The first <code>/e</code> evaluates <code>$1</code> on the replacement side and
turns it into <code>$foo</code>. The second /e starts with <code>$foo</code> and replaces
it with its value. <code>$foo</code>, then, turns into 'Fred', and that's finally
what's left in the string:
</para>
<para>
これを行う一つの方法は、置換演算子と二つの <code>/e</code> フラグを使うものです。
一つ目の <code>/e</code> は置き換え側の <code>$1</code> を評価して <code>$foo</code> に変えます。
二つ目の <code>/e</code> は <code>$foo</code> をその値に変えます。
従って、<code>$foo</code> は 'Fred' に変わって、それが結局最終的に文字列に
残されるものになります:
</para>
<verbatim><![CDATA[
$string =~ s/(\$\w+)/$1/eeg; # 'Say hello to Fred and Barney'
]]></verbatim>
<para>
The <code>/e</code> will also silently ignore violations of strict, replacing
undefined variable names with the empty string. Since I'm using the
<code>/e</code> flag (twice even!), I have all of the same security problems I 
have with <code>eval</code> in its string form. If there's something odd in
<code>$foo</code>, perhaps something like <code>@{[ system &quot;rm -rf /&quot; ]}</code>, then
I could get myself in trouble.
</para>
<para>
<code>/e</code> は暗黙のうちに struct 違反を無視するので、未定義の変数名を
空文字列に置き換えます。
<code>/e</code> フラグを (2 回も!) 使っているので、<code>eval</code> を文字列の形で使うのと
同じセキュリティ問題を全て抱えています。
もし <code>$foo</code> に(おそらく <code>@{[ system &quot;rm -rf /&quot; ]}</code> のような)変なものが
入っていたら、トラブルに出会うことになります。
</para>
<para>
To get around the security problem, I could also pull the values from
a hash instead of evaluating variable names. Using a single <code>/e</code>, I
can check the hash to ensure the value exists, and if it doesn't, I
can replace the missing value with a marker, in this case <code>???</code> to
signal that I missed something:
</para>
<para>
セキュリティ問題を避けるために、変数名を評価するのではなくハッシュから
値を取ってくることもできます。
<code>/e</code> を一つ使って、ハッシュに値があることを確認し、もしなければ、
値をマーカーに置き換えます; この場合は、<code>???</code> が何かがおかしいことの
印です;
</para>
<verbatim><![CDATA[
my $string = 'This has $foo and $bar';
]]></verbatim>
<verbatim><![CDATA[
my %Replacements = (
	foo  => 'Fred',
	);
]]></verbatim>
<verbatim><![CDATA[
# $string =~ s/\$(\w+)/$Replacements{$1}/g;
$string =~ s/\$(\w+)/
	exists $Replacements{$1} ? $Replacements{$1} : '???'
	/eg;
]]></verbatim>
<verbatim><![CDATA[
print $string;
]]></verbatim>
</sect2>
<sect2>
<title>What's wrong with always quoting &quot;$vars&quot;?</title>
<para>
(常にクォーティング &quot;$vars&quot; することの何が悪いの?)
</para>
<para>
The problem is that those double-quotes force
stringification--coercing numbers and references into strings--even
when you don't want them to be strings.  Think of it this way:
double-quote expansion is used to produce new strings.  If you already
have a string, why do you need more?
</para>
<para>
そういったダブルクォートが、強制的に文字列化(stringification)するのが問題で、
たとえそれを望んでいなくても数値やリファレンスが強制的に
文字列に変換されてしまうのです。
このように考えましょう:
ダブルクォートは新しい文字列を生成するのに使われる。
もしあなたがすでに文字列を持っているのであれば、使う必要が
あるでしょうか?
</para>
<para>
If you get used to writing odd things like these:
</para>
<para>
以下の例のような変な書き方をすると:
</para>
<verbatim><![CDATA[
print "$var";   	# BAD
$new = "$old";   	# BAD
somefunc("$var");	# BAD
]]></verbatim>
<para>
You'll be in trouble.  Those should (in 99.8% of the cases) be
the simpler and more direct:
</para>
<para>
あなたはトラブルに巻き込まれることになるでしょう。
これらは(99.8% は)、より単純、かつより直接的に書くべきなのです。
</para>
<verbatim><![CDATA[
print $var;
$new = $old;
somefunc($var);
]]></verbatim>
<para>
Otherwise, besides slowing you down, you're going to break code when
the thing in the scalar is actually neither a string nor a number, but
a reference:
</para>
<para>
さもなければ、プログラムを遅くなることのほかにも、スカラが実際には文字列でも
数値でもなくリファレンスであるようなときにあなたのプログラムが
おかしくなることになります。
</para>
<verbatim><![CDATA[
func(\@array);
sub func {
	my $aref = shift;
	my $oref = "$aref";  # WRONG
	}
]]></verbatim>
<para>
You can also get into subtle problems on those few operations in Perl
that actually do care about the difference between a string and a
number, such as the magical <code>++</code> autoincrement operator or the
syscall() function.
</para>
<para>
マジカル <code>++</code> オートインクリメント演算子や syscall() 関数のような、
文字列と数値の間の違いを実際に気にするような Perl の幾つかの操作において、
微妙な問題に直面するかもしれません。
</para>
<para>
Stringification also destroys arrays.
</para>
<para>
文字列化(stringfication)も配列を壊します。
</para>
<verbatim><![CDATA[
@lines = `command`;
print "@lines";     # WRONG - extra blanks
print @lines;       # right
]]></verbatim>
</sect2>
<sect2>
<title>Why don't my &lt;&lt;HERE documents work?</title>
<para>
(なぜ私の &lt;&lt;HERE ドキュメントがうまく動かないのでしょう?)
</para>
<para>
Check for these three things:
</para>
<para>
以下の三つの点を確認してください。
</para>
<list>
<item><itemtext>There must be no space after the &lt;&lt; part.</itemtext>
</item>
<item><itemtext>There (probably) should be a semicolon at the end.</itemtext>
</item>
<item><itemtext>You can't (easily) have any space in front of the tag.</itemtext>
</item>
<item><itemtext>&lt;&lt; パートの後ろに空白があってはいけません。</itemtext>
</item>
<item><itemtext>終端にセミコロンが置かれているかもしれません。</itemtext>
</item>
<item><itemtext>タグの前に任意のスペースを置くことはできません。</itemtext>
</item>
</list>
<para>
If you want to indent the text in the here document, you
can do this:
</para>
<para>
ヒアドキュメントのテキストでインデントを使いたいのであれば、
以下のようにしてできます:
</para>
<verbatim><![CDATA[
# all in one
($VAR = <<HERE_TARGET) =~ s/^\s+//gm;
    your text
    goes here
HERE_TARGET
]]></verbatim>
<para>
But the HERE_TARGET must still be flush against the margin.
If you want that indented also, you'll have to quote
in the indentation.
</para>
<para>
しかしこの場合も HERE_TARGET は先頭に置かなければなりません。
もしこれもインデントしたいのなら、インデントをクォートする必要があるでしょう。
</para>
<verbatim><![CDATA[
($quote = <<'    FINIS') =~ s/^\s+//gm;
        ...we will have peace, when you and all your works have
        perished--and the works of your dark master to whom you
        would deliver us. You are a liar, Saruman, and a corrupter
        of men's hearts.  --Theoden in /usr/src/perl/taint.c
    FINIS
$quote =~ s/\s+--/\n--/;
]]></verbatim>
<para>
A nice general-purpose fixer-upper function for indented here documents
follows.  It expects to be called with a here document as its argument.
It looks to see whether each line begins with a common substring, and
if so, strips that substring off.  Otherwise, it takes the amount of leading
whitespace found on the first line and removes that much off each
subsequent line.
</para>
<para>
以下はインデントされたヒアドキュメントのための汎用 fixer-upper 関数です。
この関数は引数にヒアドキュメントを渡されることを期待しています。
これは共通の部分文字列で始まる各行について、
その部分文字列を剥ぎ取るということを行います。
あるいは、最初の行の先頭にある空白を取り、
続く行に対しても同じ様に削除を行います。
</para>
<verbatim><![CDATA[
sub fix {
    local $_ = shift;
    my ($white, $leader);  # common whitespace and common leading string
    if (/^\s*(?:([^\w\s]+)(\s*).*\n)(?:\s*\1\2?.*\n)+$/) {
        ($white, $leader) = ($2, quotemeta($1));
    } else {
        ($white, $leader) = (/^(\s+)/, '');
    }
    s/^\s*?$leader(?:$white)?//gm;
    return $_;
}
]]></verbatim>
<para>
This works with leading special strings, dynamically determined:
</para>
<para>
この関数は先頭にある特別な、動的に決められる文字列に対しても使えます:
</para>
<verbatim><![CDATA[
$remember_the_main = fix<<'    MAIN_INTERPRETER_LOOP';
@@@ int
@@@ runops() {
@@@     SAVEI32(runlevel);
@@@     runlevel++;
@@@     while ( op = (*op->op_ppaddr)() );
@@@     TAINT_NOT;
@@@     return 0;
@@@ }
MAIN_INTERPRETER_LOOP
]]></verbatim>
<para>
Or with a fixed amount of leading whitespace, with remaining
indentation correctly preserved:
</para>
<para>
また、先頭にある特定の個数の空白を取り除いて、インデントを
正しく残すようなこともできます:
</para>
<verbatim><![CDATA[
$poem = fix<<EVER_ON_AND_ON;
       Now far ahead the Road has gone,
  And I must follow, if I can,
       Pursuing it with eager feet,
  Until it joins some larger way
       Where many paths and errands meet.
  And whither then? I cannot say.
	--Bilbo in /usr/src/perl/pp_ctl.c
EVER_ON_AND_ON
]]></verbatim>
</sect2>
</sect1>
<sect1>
<title>Data: Arrays</title>
<para>
(データ: 配列)
</para>
<sect2>
<title>What is the difference between a list and an array?</title>
<para>
(リストと配列の差とはなんですか?)
</para>
<para>
An array has a changeable length.  A list does not.  An array is
something you can push or pop, while a list is a set of values.  Some
people make the distinction that a list is a value while an array is a
variable. Subroutines are passed and return lists, you put things into
list context, you initialize arrays with lists, and you <code>foreach()</code>
across a list.  <code>@</code> variables are arrays, anonymous arrays are
arrays, arrays in scalar context behave like the number of elements in
them, subroutines access their arguments through the array <code>@_</code>, and
<code>push</code>/<code>pop</code>/<code>shift</code> only work on arrays.
</para>
<para>
配列は長さを変えることができます。リストはできません。
ある配列に対して push や pop ができますが、
リストに対しては値のセットしかできません。
一部には配列が変数であるのに対してリストは値であると
区別して考えている人達もいます。
リストを受け取ったり返したりするサブルーチンはリストコンテキストに
あなたを導き、リストで配列を初期化したり、<code>foreach()</code> でリストを辿ったりできます。
<code>@</code>変数は配列であり、無名配列も配列です。スカラコンテキストの配列は
その要素数のように振る舞います。
サブルーチンはその引数を <code>@_</code> という配列を通してアクセスし、
<code>push</code>/<code>pop</code>/<code>shift</code> は配列に対してのみ働きます。
</para>
<para>
As a side note, there's no such thing as a list in scalar context.
When you say
</para>
<para>
スカラコンテキストでリストとして振る舞うものはないということに
注意してください。
以下のようにすると:
</para>
<verbatim><![CDATA[
$scalar = (2, 5, 7, 9);
]]></verbatim>
<para>
you're using the comma operator in scalar context, so it uses the scalar
comma operator.  There never was a list there at all! This causes the
last value to be returned: 9.
</para>
<para>
スカラコンテキストでカンマ演算子を使ったものであり、
スカラカンマ演算子を使います。
これはリストでもなんでもありません!
この結果は最後の値である 9 となります。
</para>
</sect2>
<sect2>
<title>What is the difference between $array[1] and @array[1]?</title>
<para>
($array[1] と @array[1] との間の違いはなんですか?)
</para>
<para>
The former is a scalar value; the latter an array slice, making
it a list with one (scalar) value.  You should use $ when you want a
scalar value (most of the time) and @ when you want a list with one
scalar value in it (very, very rarely; nearly never, in fact).
</para>
<para>
前者はスカラ値であり、後者は一つのスカラ値を持ったリストを構成する
配列のスライスです。スカラ値を必要とするならば(ほとんど
の場合がこうでしょう)$を使うべきで、@ は一つのスカラ値を持った
リストを必要とするとき(実際のところ、この状況は非常に希でしょう)
に使うべきものです。
</para>
<para>
Sometimes it doesn't make a difference, but sometimes it does.
For example, compare:
</para>
<para>
これらはあるときには違いがありませんが、違いがでる場合もあります。
例えば以下のものを:
</para>
<verbatim><![CDATA[
$good[0] = `some program that outputs several lines`;
]]></verbatim>
<para>
with
</para>
<para>
次のものと比較する場合です:
</para>
<verbatim><![CDATA[
@bad[0]  = `same program that outputs several lines`;
]]></verbatim>
<para>
The <code>use warnings</code> pragma and the <strong>-w</strong> flag will warn you about these
matters.
</para>
<para>
<code>use warnings</code> プラグマと <strong>-w</strong> フラグはこのことに関する警告を行います。
</para>
</sect2>
<sect2>
<title>How can I remove duplicate elements from a list or array?</title>
<para>
(配列やリストにある重複した要素を削除するには?)
</para>
<para>
(contributed by brian d foy)
</para>
<para>
(brian d foy によって寄贈されました)
</para>
<para>
Use a hash. When you think the words &quot;unique&quot; or &quot;duplicated&quot;, think
&quot;hash keys&quot;.
</para>
<para>
ハッシュを使ってください。
「ユニーク」や「重複」といった単語を考えたときには、
「ハッシュキー」を考えてください。
</para>
<para>
If you don't care about the order of the elements, you could just
create the hash then extract the keys. It's not important how you
create that hash: just that you use <code>keys</code> to get the unique
elements.
</para>
<para>
要素の順番を気にしないなら、単にハッシュを作ってキーを取り出してください。
どのようにハッシュを作るかは重要ではありません:
単にユニークな要素を取り出すために <code>keys</code> を使うためです。
</para>
<verbatim><![CDATA[
my %hash   = map { $_, 1 } @array;
# or a hash slice: @hash{ @array } = ();
# or a foreach: $hash{$_} = 1 foreach ( @array );
]]></verbatim>
<verbatim><![CDATA[
my @unique = keys %hash;
]]></verbatim>
<para>
If you want to use a module, try the <code>uniq</code> function from
<code>List::MoreUtils</code>. In list context it returns the unique elements,
preserving their order in the list. In scalar context, it returns the
number of unique elements.
</para>
<para>
モジュールを使いたいなら、<code>List::MoreUtils</code> の <code>uniq</code> 関数を
試してみてください。
リストコンテキストでは、リストの順序を保存した形でユニークな要素を返します。
スカラコンテキストでは、ユニークな要素の数を返します。
</para>
<verbatim><![CDATA[
use List::MoreUtils qw(uniq);
]]></verbatim>
<verbatim><![CDATA[
my @unique = uniq( 1, 2, 3, 4, 4, 5, 6, 5, 7 ); # 1,2,3,4,5,6,7
my $unique = uniq( 1, 2, 3, 4, 4, 5, 6, 5, 7 ); # 7
]]></verbatim>
<para>
You can also go through each element and skip the ones you've seen
before. Use a hash to keep track. The first time the loop sees an
element, that element has no key in <code>%Seen</code>. The <code>next</code> statement
creates the key and immediately uses its value, which is <code>undef</code>, so
the loop continues to the <code>push</code> and increments the value for that
key. The next time the loop sees that same element, its key exists in
the hash <emphasis>and</emphasis> the value for that key is true (since it's not 0 or
<code>undef</code>), so the next skips that iteration and the loop goes to the
next element.
</para>
<para>
各要素を調べて、一度見つけたものをスキップすることもできます。
記録をつけるためにハッシュを使います。
ループが最初に要素を見つけると、この要素は <code>%Seen</code> にキーがありません。
<code>next</code> 文はキーを作り、直ちにその値(<code>undef</code>)を使うので、
ループは <code>push</code> を続行し、このキーの値をインクリメントします。
次回にループが同じ要素を見つけると、ハッシュにはそのキーが存在し、
<emphasis>かつ</emphasis> そのキーの値が(0 でも <code>undef</code> でもないので)真なので、
next は反復をスキップし、ループは次の要素に進みます。
</para>
<verbatim><![CDATA[
my @unique = ();
my %seen   = ();
]]></verbatim>
<verbatim><![CDATA[
foreach my $elem ( @array )
	{
	next if $seen{ $elem }++;
	push @unique, $elem;
	}
]]></verbatim>
<para>
You can write this more briefly using a grep, which does the
same thing.
</para>
<para>
grep を使うことでより簡単に書くこともでき、これは同じことになります。
</para>
<verbatim><![CDATA[
my %seen = ();
my @unique = grep { ! $seen{ $_ }++ } @array;
]]></verbatim>
</sect2>
<sect2>
<title>How can I tell whether a certain element is contained in a list or array?</title>
<para>
(リストや配列の内容にある特定の要素があるかどうかを確かめるには?)
</para>
<para>
(portions of this answer contributed by Anno Siegel)
</para>
<para>
(この回答の一部は Anno Siegel によって寄贈されました)
</para>
<para>
Hearing the word &quot;in&quot; is an <emphasis>in</emphasis>dication that you probably should have
used a hash, not a list or array, to store your data.  Hashes are
designed to answer this question quickly and efficiently.  Arrays aren't.
</para>
<para>
ハッシュはこの質問に対する速くて効率の良い解答のために
デザインされています。
配列はそうではありません。
</para>
<para>
That being said, there are several ways to approach this.  If you
are going to make this query many times over arbitrary string values,
the fastest way is probably to invert the original array and maintain a
hash whose keys are the first array's values.
</para>
<para>
幾つかのやり方がありますが、この問い合わせを多くのアイテムに対して
行いたいとか、値が任意の文字列である場合には最も速いやり方は元の
配列の逆のものを作って元の配列の値をキーとするようなハッシュを
管理するというものです。
</para>
<verbatim><![CDATA[
@blues = qw/azure cerulean teal turquoise lapis-lazuli/;
%is_blue = ();
for (@blues) { $is_blue{$_} = 1 }
]]></verbatim>
<para>
Now you can check whether <code>$is_blue{$some_color}</code>.  It might have
been a good idea to keep the blues all in a hash in the first place.
</para>
<para>
こうすれば、<code>$is_blue{$some_color}</code> がどうであるかでチェックすることができます。
最初の場所で bules にハッシュのすべてを保持させるのはよい考えでしょう。
</para>
<para>
If the values are all small integers, you could use a simple indexed
array.  This kind of an array will take up less space:
</para>
<para>
値のすべてが小さな整数であれば、単純な添え字付き配列を使うことができます。
この種の配列はより少ない場所しか使いません。
</para>
<verbatim><![CDATA[
@primes = (2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31);
@is_tiny_prime = ();
for (@primes) { $is_tiny_prime[$_] = 1 }
# or simply  @istiny_prime[@primes] = (1) x @primes;
]]></verbatim>
<para>
Now you check whether $is_tiny_prime[$some_number].
</para>
<para>
これで $is_tiny_prime[$some_number] の内容がどうであるかで
チェックすることができます。
</para>
<para>
If the values in question are integers instead of strings, you can save
quite a lot of space by using bit strings instead:
</para>
<para>
問い合わせる値が文字列ではなく整数であるのならば、ビットストリングを
使うことによって大幅に空間を節約することができます。
</para>
<verbatim><![CDATA[
@articles = ( 1..10, 150..2000, 2017 );
undef $read;
for (@articles) { vec($read,$_,1) = 1 }
]]></verbatim>
<para>
Now check whether <code>vec($read,$n,1)</code> is true for some <code>$n</code>.
</para>
<para>
これで <code>vec($read,$n,1)</code> が真かどうかで <code>$n</code> の検査ができます。
</para>
<para>
These methods guarantee fast individual tests but require a re-organization
of the original list or array.  They only pay off if you have to test
multiple values against the same array.
</para>
<para>
これらのメソッドは個々のテストの速さが保証されていますが、
元のリストや配列の再構成が必要です。
同じ配列に対して複数の値をテストする必要がある場合にのみ元が取れます。
</para>
<para>
If you are testing only once, the standard module <code>List::Util</code> exports
the function <code>first</code> for this purpose.  It works by stopping once it
finds the element. It's written in C for speed, and its Perl equivalent
looks like this subroutine:
</para>
<para>
一度だけテストする場合、標準モジュール <code>List::Util</code> がこの目的のために
<code>first</code> 関数をエクスポートしています。
これは要素を見つけると停止することで動作します。
速度のために C で書かれていて、これの Perl の等価な処理は、次のサブルーチンの
ようになります:
</para>
<verbatim><![CDATA[
sub first (&@) {
	my $code = shift;
	foreach (@_) {
		return $_ if &{$code}();
	}
	undef;
}
]]></verbatim>
<para>
If speed is of little concern, the common idiom uses grep in scalar context
(which returns the number of items that passed its condition) to traverse the
entire list. This does have the benefit of telling you how many matches it
found, though.
</para>
<para>
速度が問題ではないなら、一般的な方法は、リスト全体をトラバースするために
grep をスカラコンテキストで使う(これで条件をパスしたアイテムの数を返します)
ことです。
しかし、これには何回マッチングしたのかを知らせるという利点があります。
</para>
<verbatim><![CDATA[
my $is_there = grep $_ eq $whatever, @array;
]]></verbatim>
<para>
If you want to actually extract the matching elements, simply use grep in
list context.
</para>
<para>
実際にマッチングした要素を展開したい場合は、単にリストコンテキストで
grep を使ってください。
</para>
<verbatim><![CDATA[
my @matches = grep $_ eq $whatever, @array;
]]></verbatim>
</sect2>
<sect2>
<title>How do I compute the difference of two arrays?  How do I compute the intersection of two arrays?</title>
<para>
(二つの配列の差(difference)を求めるには? 二つの配列の共通要素(inter section)を求めるには?)
</para>
<para>
Use a hash.  Here's code to do both and more.  It assumes that each
element is unique in a given array:
</para>
<para>
ハッシュを使います。
以下のプログラム片は質問の両方を行います。
与えられた配列の要素には重複がないと仮定しています。
</para>
<verbatim><![CDATA[
@union = @intersection = @difference = ();
%count = ();
foreach $element (@array1, @array2) { $count{$element}++ }
foreach $element (keys %count) {
	push @union, $element;
	push @{ $count{$element} > 1 ? \@intersection : \@difference }, $element;
	}
]]></verbatim>
<para>
Note that this is the <emphasis>symmetric difference</emphasis>, that is, all elements
in either A or in B but not in both.  Think of it as an xor operation.
</para>
<para>
これは <emphasis>対称的差分</emphasis>、つまり、A か B のどちらかにあって、
両方にあることはない全ての要素である、ということに注意してください。
これは xor 操作のようなものと考えてください。
</para>
</sect2>
<sect2>
<title>How do I test whether two arrays or hashes are equal?</title>
<para>
(二つの配列や二つのハッシュが等しいかどうかを検査するには?)
</para>
<para>
The following code works for single-level arrays.  It uses a
stringwise comparison, and does not distinguish defined versus
undefined empty strings.  Modify if you have other needs.
</para>
<para>
以下に挙げる例は一レベルの配列に対して有効です。
これは文字列としての比較を使い、定義済みと未定義の空文字列を区別しません。
必要に応じて修正してください。
</para>
<verbatim><![CDATA[
$are_equal = compare_arrays(\@frogs, \@toads);
]]></verbatim>
<verbatim><![CDATA[
sub compare_arrays {
	my ($first, $second) = @_;
	no warnings;  # silence spurious -w undef complaints
	return 0 unless @$first == @$second;
	for (my $i = 0; $i < @$first; $i++) {
		return 0 if $first->[$i] ne $second->[$i];
		}
	return 1;
	}
]]></verbatim>
<para>
For multilevel structures, you may wish to use an approach more
like this one.  It uses the CPAN module <code>FreezeThaw</code>:
</para>
<para>
多重レベル構造に対応するために、あなたは以下のような手段を使いたいと
考えるかもしれません。
ここでは CPAN モジュールの <code>FreezeThaw</code> を使っています:
</para>
<verbatim><![CDATA[
use FreezeThaw qw(cmpStr);
@a = @b = ( "this", "that", [ "more", "stuff" ] );
]]></verbatim>
<verbatim><![CDATA[
printf "a and b contain %s arrays\n",
	cmpStr(\@a, \@b) == 0
	? "the same"
	: "different";
]]></verbatim>
<para>
This approach also works for comparing hashes.  Here we'll demonstrate
two different answers:
</para>
<para>
このアプローチはハッシュの比較にも使えます。
以下に二種類の回答をお見せしましょう:
</para>
<verbatim><![CDATA[
use FreezeThaw qw(cmpStr cmpStrHard);
]]></verbatim>
<verbatim><![CDATA[
%a = %b = ( "this" => "that", "extra" => [ "more", "stuff" ] );
$a{EXTRA} = \%b;
$b{EXTRA} = \%a;
]]></verbatim>
<verbatim><![CDATA[
printf "a and b contain %s hashes\n",
cmpStr(\%a, \%b) == 0 ? "the same" : "different";
]]></verbatim>
<verbatim><![CDATA[
printf "a and b contain %s hashes\n",
cmpStrHard(\%a, \%b) == 0 ? "the same" : "different";
]]></verbatim>
<para>
The first reports that both those the hashes contain the same data,
while the second reports that they do not.  Which you prefer is left as
an exercise to the reader.
</para>
<para>
最初のものは二つのハッシュが同じ内容であると報告しますが、二番目の
ものは違うと報告します。
</para>
</sect2>
<sect2>
<title>How do I find the first array element for which a condition is true?</title>
<para>
(ある条件が真となる最初の配列要素を見つけだすには?)
</para>
<para>
To find the first array element which satisfies a condition, you can
use the <code>first()</code> function in the <code>List::Util</code> module, which comes
with Perl 5.8. This example finds the first element that contains
&quot;Perl&quot;.
</para>
<para>
条件を満たす最初の配列要素を探すためには、Perl 5.8 から同梱されている
<code>List::Util</code> モジュールの <code>first()</code> 関数が使えます。
この例は &quot;Perl&quot; を含む最初の要素を探します。
</para>
<verbatim><![CDATA[
use List::Util qw(first);
]]></verbatim>
<verbatim><![CDATA[
my $element = first { /Perl/ } @array;
]]></verbatim>
<para>
If you cannot use <code>List::Util</code>, you can make your own loop to do the
same thing.  Once you find the element, you stop the loop with last.
</para>
<para>
<code>List::Util</code> が使えない場合は、同じことをするために自分でループを書きます。
要素が見つかったら、last を使ってループを停止します。
</para>
<verbatim><![CDATA[
my $found;
foreach ( @array ) {
	if( /Perl/ ) { $found = $_; last }
	}
]]></verbatim>
<para>
If you want the array index, you can iterate through the indices
and check the array element at each index until you find one
that satisfies the condition.
</para>
<para>
配列の添え字がほしい場合は、添え字に順番に変えていって、
それぞれの添え字の配列要素をチェックして、条件を満たすものが
見つかるまで繰り返します。
</para>
<verbatim><![CDATA[
my( $found, $index ) = ( undef, -1 );
for( $i = 0; $i < @array; $i++ ) {
	if( $array[$i] =~ /Perl/ ) {
		$found = $array[$i];
		$index = $i;
		last;
		}
	}
]]></verbatim>
</sect2>
<sect2>
<title>How do I handle linked lists?</title>
<para>
(リンク付きリストを扱うには?)
</para>
<para>
In general, you usually don't need a linked list in Perl, since with
regular arrays, you can push and pop or shift and unshift at either
end, or you can use splice to add and/or remove arbitrary number of
elements at arbitrary points.  Both pop and shift are O(1)
operations on Perl's dynamic arrays.  In the absence of shifts and
pops, push in general needs to reallocate on the order every log(N)
times, and unshift will need to copy pointers each time.
</para>
<para>
一般的には、Perl ではリンク付きリストを扱う必要はありません。
なぜなら、通常の配列を使って push や pop、shift や unsift を使って両端で
操作できたり、splice を使って任意の場所にある任意個の要素を加えたり
削除したりすることができるからです。
pop と shift は両方ともが、Perl の動的配列に対する O(1) の操作です。
shift や pop がなかった場合、push は一般的には log(N) 回毎のオーダーで
再割り当てが必要になります。
そして unshift は呼ばれる毎にポインターのコピーが必要になるでしょう。
</para>
<para>
If you really, really wanted, you could use structures as described in
<link xref='perldsc'>perldsc</link> or <link xref='perltoot'>perltoot</link> and do just what the algorithm book tells
you to do.  For example, imagine a list node like this:
</para>
<para>
もし、本当に、本当にリンク付きリストを使いたいのなら、<link xref='perldsc'>perldsc</link> や
<link xref='perltoot'>perltoot</link> で説明されているようなデータ構造を使うことができ、
アルゴリズムの教科書にあるようなことができます。
例えば以下のようなリストノードをを考えてみましょう:
</para>
<verbatim><![CDATA[
$node = {
	VALUE => 42,
	LINK  => undef,
	};
]]></verbatim>
<para>
You could walk the list this way:
</para>
<para>
リストを渡り歩くには以下のようにします:
</para>
<verbatim><![CDATA[
print "List: ";
for ($node = $head;  $node; $node = $node->{LINK}) {
	print $node->{VALUE}, " ";
	}
print "\n";
]]></verbatim>
<para>
You could add to the list this way:
</para>
<para>
以下のやり方でリストに追加できます:
</para>
<verbatim><![CDATA[
my ($head, $tail);
$tail = append($head, 1);       # grow a new head
for $value ( 2 .. 10 ) {
	$tail = append($tail, $value);
	}
]]></verbatim>
<verbatim><![CDATA[
sub append {
	my($list, $value) = @_;
	my $node = { VALUE => $value };
	if ($list) {
		$node->{LINK} = $list->{LINK};
		$list->{LINK} = $node;
		}
	else {
		$_[0] = $node;      # replace caller's version
		}
	return $node;
	}
]]></verbatim>
<para>
But again, Perl's built-in are virtually always good enough.
</para>
<para>
しかし繰り返しますが、Perl の組み込み型は事実上常に充分なものなのです。
</para>
</sect2>
<sect2>
<title>How do I handle circular lists?</title>
<para>
(循環リスト(circular list)を扱うには?)
</para>
<para>
Circular lists could be handled in the traditional fashion with linked
lists, or you could just do something like this with an array:
</para>
<para>
循環リストはリンク付きリストを使って伝統的なやり方で扱うことができます。
あるいは以下のように配列を使って行うこともできます:
</para>
<verbatim><![CDATA[
unshift(@array, pop(@array));  # the last shall be first
push(@array, shift(@array));   # and vice versa
]]></verbatim>
<para>
You can also use <code>Tie::Cycle</code>:
</para>
<para>
<code>Tie::Cycle</code> を使うこともできます:
</para>
<verbatim><![CDATA[
use Tie::Cycle;
]]></verbatim>
<verbatim><![CDATA[
tie my $cycle, 'Tie::Cycle', [ qw( FFFFFF 000000 FFFF00 ) ];
]]></verbatim>
<verbatim><![CDATA[
print $cycle; # FFFFFF
print $cycle; # 000000
print $cycle; # FFFF00
]]></verbatim>
</sect2>
<sect2>
<title>How do I shuffle an array randomly?</title>
<para>
(配列をランダムにかき混ぜるには?)
</para>
<para>
If you either have Perl 5.8.0 or later installed, or if you have
Scalar-List-Utils 1.03 or later installed, you can say:
</para>
<para>
Perl 5.8.0 以降がインストールされているか、Scalar-List-Utils 1.03 以降が
インストールされているなら、以下のように出来ます:
</para>
<verbatim><![CDATA[
use List::Util 'shuffle';
]]></verbatim>
<verbatim><![CDATA[
@shuffled = shuffle(@list);
]]></verbatim>
<para>
If not, you can use a Fisher-Yates shuffle.
</para>
<para>
そうでないなら、Fisher-Yates 法が使えます。
</para>
<verbatim><![CDATA[
sub fisher_yates_shuffle {
	my $deck = shift;  # $deck is a reference to an array
	my $i = @$deck;
	while (--$i) {
		my $j = int rand ($i+1);
		@$deck[$i,$j] = @$deck[$j,$i];
		}
}
]]></verbatim>
<verbatim><![CDATA[
# shuffle my mpeg collection
#
my @mpeg = <audio/*/*.mp3>;
fisher_yates_shuffle( \@mpeg );    # randomize @mpeg in place
print @mpeg;
]]></verbatim>
<para>
Note that the above implementation shuffles an array in place,
unlike the <code>List::Util::shuffle()</code> which takes a list and returns
a new shuffled list.
</para>
<para>
<code>List::Util::shuffle()</code> はリストを受け取って、混ぜられた新しいリストを
返しますが、上記の実装は配列そのものを混ぜることに注意してください。
</para>
<para>
You've probably seen shuffling algorithms that work using splice,
randomly picking another element to swap the current element with
</para>
<para>
splice を使ったシャッフルアルゴリズムを見たことがあるかもしれません。
カレントの要素をランダムに取り出した別の要素と交換します:
</para>
<verbatim><![CDATA[
srand;
@new = ();
@old = 1 .. 10;  # just a demo
while (@old) {
	push(@new, splice(@old, rand @old, 1));
	}
]]></verbatim>
<para>
This is bad because splice is already O(N), and since you do it N
times, you just invented a quadratic algorithm; that is, O(N**2).
This does not scale, although Perl is so efficient that you probably
won't notice this until you have rather largish arrays.
</para>
<para>
これは splice が O(N) であり、さらにそれを N 回呼んでいるのですから
良くありません。
つまりこれは O(N**2) のアルゴリズムです。
これは大きな配列に使わなければあなたはその効率の悪さに気がつかないでしょう。
</para>
</sect2>
<sect2>
<title>How do I process/modify each element of an array?</title>
<para>
(配列の各要素に対する処理や、変更を行うには?)
</para>
<para>
Use <code>for</code>/<code>foreach</code>:
</para>
<para>
<code>for</code>/<code>foreach</code> を使います:
</para>
<verbatim><![CDATA[
for (@lines) {
	s/foo/bar/;	# change that word
	tr/XZ/ZX/;	# swap those letters
	}
]]></verbatim>
<para>
Here's another; let's compute spherical volumes:
</para>
<para>
別の方法です; 球の体積を求めます:
</para>
<verbatim><![CDATA[
for (@volumes = @radii) {   # @volumes has changed parts
	$_ **= 3;
	$_ *= (4/3) * 3.14159;  # this will be constant folded
	}
]]></verbatim>
<para>
which can also be done with <code>map()</code> which is made to transform
one list into another:
</para>
<para>
リストを他のリストに変換する <code>map()</code> を使っても行えます:
</para>
<verbatim><![CDATA[
@volumes = map {$_ ** 3 * (4/3) * 3.14159} @radii;
]]></verbatim>
<para>
If you want to do the same thing to modify the values of the
hash, you can use the <code>values</code> function.  As of Perl 5.6
the values are not copied, so if you modify $orbit (in this
case), you modify the value.
</para>
<para>
同じことをハッシュの値に対して行いたいのであれば、<code>values</code> は使えません。
Perl 5.6 以降では値はコピーされないので、(この場合では) $orbit を変更すると、
値を変更することになります。
</para>
<verbatim><![CDATA[
for $orbit ( values %orbits ) {
	($orbit **= 3) *= (4/3) * 3.14159;
	}
]]></verbatim>
<para>
Prior to perl 5.6 <code>values</code> returned copies of the values,
so older perl code often contains constructions such as
<code>@orbits{keys %orbits}</code> instead of <code>values %orbits</code> where
the hash is to be modified.
</para>
<para>
perl 5.6 以前では、<code>values</code> は値のコピーを返すので、古い perl の
コードでは、ハッシュを修正しているところで  <code>values %orbits</code> ではなく
<code>@orbits{keys %orbits}</code> と書いていることがよくあります。
</para>
</sect2>
<sect2>
<title>How do I select a random element from an array?</title>
<para>
(ある配列からランダムに要素を選択するには?)
</para>
<para>
Use the <code>rand()</code> function (see <link xref='perlfunc#rand'>perlfunc/rand</link>):
</para>
<para>
<code>rand()</code> 関数を使います(<link xref='perlfunc#rand'>perlfunc/rand</link> を参照):
</para>
<verbatim><![CDATA[
$index   = rand @array;
$element = $array[$index];
]]></verbatim>
<para>
Or, simply:
</para>
<para>
あるいは、単純に:
</para>
<verbatim><![CDATA[
my $element = $array[ rand @array ];
]]></verbatim>
</sect2>
<sect2>
<title>How do I permute N elements of a list?
<index>List::Permuter</index> <index>permute</index> <index>Algorithm::Loops</index> <index>Knuth</index>
<index>The Art of Computer Programming</index> <index>Fischer-Krause</index></title>
<para>
(N 要素を持つリストの順列(permute)を求めるには?)
</para>
<para>
Use the <code>List::Permutor</code> module on CPAN. If the list is actually an
array, try the <code>Algorithm::Permute</code> module (also on CPAN). It's
written in XS code and is very efficient:
</para>
<para>
CPAN にある <code>List::Permutor</code> モジュールを使ってください。
リストが実際には配列なら、<code>Algorithm::Permute</code> モジュール(これも CPAN に
あります)を試してください。
これは XS コードで書かれていて、とても効率的です:
</para>
<verbatim><![CDATA[
use Algorithm::Permute;
]]></verbatim>
<verbatim><![CDATA[
my @array = 'a'..'d';
my $p_iterator = Algorithm::Permute->new ( \@array );
]]></verbatim>
<verbatim><![CDATA[
while (my @perm = $p_iterator->next) {
   print "next permutation: (@perm)\n";
	}
]]></verbatim>
<para>
For even faster execution, you could do:
</para>
<para>
より速い実行のために、以下のようにも出来ます:
</para>
<verbatim><![CDATA[
use Algorithm::Permute;
]]></verbatim>
<verbatim><![CDATA[
my @array = 'a'..'d';
]]></verbatim>
<verbatim><![CDATA[
Algorithm::Permute::permute {
	print "next permutation: (@array)\n";
	} @array;
]]></verbatim>
<para>
Here's a little program that generates all permutations of all the
words on each line of input. The algorithm embodied in the
<code>permute()</code> function is discussed in Volume 4 (still unpublished) of
Knuth's <emphasis>The Art of Computer Programming</emphasis> and will work on any list:
</para>
<para>
以下の小さなプログラムは入力された行にある各単語の順列をすべて生成します。
関数 permute() で使われているアルゴリズムは
Knuth の <emphasis>The Art of Computer Programming</emphasis> の Volume 4 (未発行) で
議論されていて、任意のリストで動作するはずです:
</para>
<verbatim><![CDATA[
#!/usr/bin/perl -n
# Fischer-Krause ordered permutation generator
]]></verbatim>
<verbatim><![CDATA[
sub permute (&@) {
	my $code = shift;
	my @idx = 0..$#_;
	while ( $code->(@_[@idx]) ) {
		my $p = $#idx;
		--$p while $idx[$p-1] > $idx[$p];
		my $q = $p or return;
		push @idx, reverse splice @idx, $p;
		++$q while $idx[$p-1] > $idx[$q];
		@idx[$p-1,$q]=@idx[$q,$p-1];
	}
}
]]></verbatim>
<verbatim><![CDATA[
permute { print "@_\n" } split;
]]></verbatim>
<para>
The <code>Algorithm::Loops</code> module also provides the <code>NextPermute</code> and
<code>NextPermuteNum</code> functions which efficiently find all unique permutations
of an array, even if it contains duplicate values, modifying it in-place:
if its elements are in reverse-sorted order then the array is reversed,
making it sorted, and it returns false; otherwise the next
permutation is returned.
</para>
<para>
<code>Algorithm::Loops</code> モジュールも the <code>NextPermute</code> と <code>NextPermuteNum</code> の
関数を提供していて、重複した値が含まれていても、その場で変更して、配列の
全てのユニークな順列を探します:
もしその要素が逆順にソートされているなら、配列を反転させて、ソートを
行い、偽を返します; さもなければ次の順列を返します。
</para>
<para>
<code>NextPermute</code> uses string order and <code>NextPermuteNum</code> numeric order, so
you can enumerate all the permutations of <code>0..9</code> like this:
</para>
<para>
<code>NextPermute</code> は文字列順を使い、<code>NextPermuteNum</code> は数値順を使うので、
<code>0..9</code> の全ての順番を数え上げるには以下のようにします:
</para>
<verbatim><![CDATA[
use Algorithm::Loops qw(NextPermuteNum);
]]></verbatim>
<verbatim><![CDATA[
my @list= 0..9;
do { print "@list\n" } while NextPermuteNum @list;
]]></verbatim>
</sect2>
<sect2>
<title>How do I sort an array by (anything)?</title>
<para>
((なにか)で配列をソートするには?)
</para>
<para>
Supply a comparison function to sort() (described in <link xref='perlfunc#sort'>perlfunc/sort</link>):
</para>
<para>
sort() (<link xref='perlfunc#sort'>perlfunc/sort</link> に説明があります)のための比較関数を作ります:
</para>
<verbatim><![CDATA[
@list = sort { $a <=> $b } @list;
]]></verbatim>
<para>
The default sort function is cmp, string comparison, which would
sort <code>(1, 2, 10)</code> into <code>(1, 10, 2)</code>.  <code>&lt;=&gt;</code>, used above, is
the numerical comparison operator.
</para>
<para>
デフォルトのソート関数は文字列比較である cmp で、<code>(1, 2, 10)</code> を 
<code>(1, 10, 2)</code> に並び変えます。
上の例では、数値比較演算子である <code>&lt;=&gt;</code> を使っています。
</para>
<para>
If you have a complicated function needed to pull out the part you
want to sort on, then don't do it inside the sort function.  Pull it
out first, because the sort BLOCK can be called many times for the
same element.  Here's an example of how to pull out the first word
after the first number on each item, and then sort those words
case-insensitively.
</para>
<para>
ソートするものの一部を取り出す必要があるような複雑な関数を使うのなら、
ソート関数の内側でそれを使ってはいけません。
最初にその関数で使う部分を取り出します。
なぜなら、sort BLOCK は同じ要素に対して何度も何度も呼び出される
可能性があるからです。
以下の例は、各アイテムの最初の番号の後にある最初の単語を取り出し、
その後でそれらの単語を大小文字を無視してソートします。
</para>
<verbatim><![CDATA[
@idx = ();
for (@data) {
	($item) = /\d+\s*(\S+)/;
	push @idx, uc($item);
    }
@sorted = @data[ sort { $idx[$a] cmp $idx[$b] } 0 .. $#idx ];
]]></verbatim>
<para>
which could also be written this way, using a trick
that's come to be known as the Schwartzian Transform:
</para>
<para>
これはシュワルツ変換と呼ばれるトリックを使って以下のように
書くこともできます:
</para>
<verbatim><![CDATA[
@sorted = map  { $_->[0] }
	sort { $a->[1] cmp $b->[1] }
	map  { [ $_, uc( (/\d+\s*(\S+)/)[0]) ] } @data;
]]></verbatim>
<para>
If you need to sort on several fields, the following paradigm is useful.
</para>
<para>
幾つかのフィールドを使ってソートする必要があるのなら、
以下のやり方が便利でしょう。
</para>
<verbatim><![CDATA[
@sorted = sort {
	field1($a) <=> field1($b) ||
	field2($a) cmp field2($b) ||
	field3($a) cmp field3($b)
	} @data;
]]></verbatim>
<para>
This can be conveniently combined with precalculation of keys as given
above.
</para>
<para>
これは先の例にあったキーの precalculation と組み合わせることも
できます。
</para>
<para>
See the <filename>sort</filename> article in the &quot;Far More Than You Ever Wanted
To Know&quot; collection in <xlink uri='http://www.cpan.org/misc/olddoc/FMTEYEWTK.tgz'>http://www.cpan.org/misc/olddoc/FMTEYEWTK.tgz</xlink> for
more about this approach.
</para>
<para>
この手法に関する更なる情報については
<xlink uri='http://www.cpan.org/misc/olddoc/FMTEYEWTK.tgz'>http://www.cpan.org/misc/olddoc/FMTEYEWTK.tgz</xlink> にある
&quot;Far More Than You Ever Wanted To Know&quot; コレクションの <filename>sort</filename> という記事を
参照してください。
</para>
<para>
See also the question later in <link xref='perlfaq4'>perlfaq4</link> on sorting hashes.
</para>
<para>
<link xref='perlfaq4'>perlfaq4</link> で後述する、ハッシュのソートに関する質問も参照してください。
</para>
</sect2>
<sect2>
<title>How do I manipulate arrays of bits?</title>
<para>
(ビット配列を扱うには?)
</para>
<para>
Use <code>pack()</code> and <code>unpack()</code>, or else <code>vec()</code> and the bitwise
operations.
</para>
<para>
<code>pack()</code> と <code>unpack()</code> か、<code>vec()</code> とビット演算を使います。
</para>
<para>
For example, this sets <code>$vec</code> to have bit N set if <code>$ints[N]</code> was
set:
</para>
<para>
以下の例は、<code>$ints[N]</code> がセットされていれば <code>$vec</code> の bit N をセットします。
</para>
<verbatim><![CDATA[
$vec = '';
foreach(@ints) { vec($vec,$_,1) = 1 }
]]></verbatim>
<para>
Here's how, given a vector in <code>$vec</code>, you can get those bits into your
<code>@ints</code> array:
</para>
<para>
次に挙げる例は、<code>$vec</code> で与えられるベクターのビットを配列 <code>@ints</code> に
取り出すものです:
</para>
<verbatim><![CDATA[
sub bitvec_to_list {
	my $vec = shift;
	my @ints;
	# Find null-byte density then select best algorithm
	if ($vec =~ tr/\0// / length $vec > 0.95) {
		use integer;
		my $i;
]]></verbatim>
<verbatim><![CDATA[
# This method is faster with mostly null-bytes
while($vec =~ /[^\0]/g ) {
	$i = -9 + 8 * pos $vec;
	push @ints, $i if vec($vec, ++$i, 1);
	push @ints, $i if vec($vec, ++$i, 1);
	push @ints, $i if vec($vec, ++$i, 1);
	push @ints, $i if vec($vec, ++$i, 1);
	push @ints, $i if vec($vec, ++$i, 1);
	push @ints, $i if vec($vec, ++$i, 1);
	push @ints, $i if vec($vec, ++$i, 1);
	push @ints, $i if vec($vec, ++$i, 1);
	}
}
		else {
# This method is a fast general algorithm
use integer;
my $bits = unpack "b*", $vec;
push @ints, 0 if $bits =~ s/^(\d)// && $1;
push @ints, pos $bits while($bits =~ /1/g);
}
]]></verbatim>
<verbatim><![CDATA[
return \@ints;
}
]]></verbatim>
<para>
This method gets faster the more sparse the bit vector is.
(Courtesy of Tim Bunce and Winfried Koenig.)
</para>
<para>
この方法はビットベクターが疎であるときにさらに高速になります
(Tim Bunce と Winfried Koenig によるものです)。
</para>
<para>
You can make the while loop a lot shorter with this suggestion
from Benjamin Goldberg:
</para>
<para>
Benjamin Goldberg の提案を使って、while ループをはるかに
短くすることもできます:
</para>
<verbatim><![CDATA[
while($vec =~ /[^\0]+/g ) {
	push @ints, grep vec($vec, $_, 1), $-[0] * 8 .. $+[0] * 8;
	}
]]></verbatim>
<para>
Or use the CPAN module <code>Bit::Vector</code>:
</para>
<para>
または CPAN の <code>Bit::Vector</code> モジュールを使います:
</para>
<verbatim><![CDATA[
$vector = Bit::Vector->new($num_of_bits);
$vector->Index_List_Store(@ints);
@ints = $vector->Index_List_Read();
]]></verbatim>
<para>
<code>Bit::Vector</code> provides efficient methods for bit vector, sets of
small integers and &quot;big int&quot; math.
</para>
<para>
<code>Bit::Vector</code> は、ビットベクタ、小さい整数の就業、「大きな整数」の
計算に関する効果的なメソッドを提供します。
</para>
<para>
Here's a more extensive illustration using vec():
</para>
<para>
以下は、vec() を使った広範囲な説明です:
</para>
<verbatim><![CDATA[
# vec demo
$vector = "\xff\x0f\xef\xfe";
print "Ilya's string \\xff\\x0f\\xef\\xfe represents the number ",
unpack("N", $vector), "\n";
$is_set = vec($vector, 23, 1);
print "Its 23rd bit is ", $is_set ? "set" : "clear", ".\n";
pvec($vector);
]]></verbatim>
<verbatim><![CDATA[
set_vec(1,1,1);
set_vec(3,1,1);
set_vec(23,1,1);
]]></verbatim>
<verbatim><![CDATA[
set_vec(3,1,3);
set_vec(3,2,3);
set_vec(3,4,3);
set_vec(3,4,7);
set_vec(3,8,3);
set_vec(3,8,7);
]]></verbatim>
<verbatim><![CDATA[
set_vec(0,32,17);
set_vec(1,32,17);
]]></verbatim>
<verbatim><![CDATA[
sub set_vec {
	my ($offset, $width, $value) = @_;
	my $vector = '';
	vec($vector, $offset, $width) = $value;
	print "offset=$offset width=$width value=$value\n";
	pvec($vector);
	}
]]></verbatim>
<verbatim><![CDATA[
sub pvec {
	my $vector = shift;
	my $bits = unpack("b*", $vector);
	my $i = 0;
	my $BASE = 8;
]]></verbatim>
<verbatim><![CDATA[
print "vector length in bytes: ", length($vector), "\n";
@bytes = unpack("A8" x length($vector), $bits);
print "bits are: @bytes\n\n";
}
]]></verbatim>
</sect2>
<sect2>
<title>Why does defined() return true on empty arrays and hashes?</title>
<para>
(なぜ空の配列やハッシュに defined() を使ったときに真が返ってくるのでしょう?)
</para>
<para>
The short story is that you should probably only use defined on scalars or
functions, not on aggregates (arrays and hashes).  See <link xref='perlfunc#defined'>perlfunc/defined</link>
in the 5.004 release or later of Perl for more detail.
</para>
<para>
簡単にいえば、スカラや関数に対してのみ defined を使うべきで、
集成体(aggregates, 配列やハッシュ)に対して使うべきではないのです。
詳しくは 5.004 以降の <link xref='perlfunc#defined'>perlfunc/defined</link> を参照してください。
</para>
</sect2>
</sect1>
<sect1>
<title>Data: Hashes (Associative Arrays)</title>
<para>
(データ: ハッシュ(連想配列))
</para>
<sect2>
<title>How do I process an entire hash?</title>
<para>
(ハッシュ全体を処理するには?)
</para>
<para>
(contributed by brian d foy)
</para>
<para>
(brian d foy によって寄贈されました)
</para>
<para>
There are a couple of ways that you can process an entire hash. You
can get a list of keys, then go through each key, or grab a one
key-value pair at a time.
</para>
<para>
ハッシュ全体を処理するには二つの方法があります。
キーのリストを取得してからキー毎に処理するか、一度に一つのキー-値の
ペアを取得するかです。
</para>
<para>
To go through all of the keys, use the <code>keys</code> function. This extracts
all of the keys of the hash and gives them back to you as a list. You
can then get the value through the particular key you're processing:
</para>
<para>
全てのキーを得るには、<code>keys</code> 関数を使います。
ハッシュの全てのキーを展開してリストの形で返します。
それから処理したい特定のキーの値を取得します。
</para>
<verbatim><![CDATA[
foreach my $key ( keys %hash ) {
	my $value = $hash{$key}
	...
	}
]]></verbatim>
<para>
Once you have the list of keys, you can process that list before you
process the hashh elements. For instance, you can sort the keys so you
can process them in lexical order:
</para>
<para>
キーのリストを取得したら、ハッシュ要素を処理する前にリストを処理できます。
例えば、キーをソートしてレキシカルな順序で処理できます:
</para>
<verbatim><![CDATA[
foreach my $key ( sort keys %hash ) {
	my $value = $hash{$key}
	...
	}
]]></verbatim>
<para>
Or, you might want to only process some of the items. If you only want
to deal with the keys that start with <code>text:</code>, you can select just
those using <code>grep</code>:
</para>
<para>
あるいは、アイテムの一部に対してのみ処理したいかもしれません。
キーが <code>text:</code> で始まるキーのみ扱いたいなら、単に <code>grep</code> を使って
選択できます:
</para>
<verbatim><![CDATA[
foreach my $key ( grep /^text:/, keys %hash ) {
	my $value = $hash{$key}
	...
	}
]]></verbatim>
<para>
If the hash is very large, you might not want to create a long list of
keys. To save some memory, you can grab on key-value pair at a time using
<code>each()</code>, which returns a pair you haven't seen yet:
</para>
<para>
ハッシュがとても大きい場合、キーの長いリストを作りたくないかもしれません。
メモリを節約するために、まだ取得していないキー-値の組を返す <code>each()</code> を
使って組を取得できます:
</para>
<verbatim><![CDATA[
while( my( $key, $value ) = each( %hash ) ) {
	...
	}
]]></verbatim>
<para>
The <code>each</code> operator returns the pairs in apparently random order, so if
ordering matters to you, you'll have to stick with the <code>keys</code> method.
</para>
<para>
<code>each</code> 演算子は組を一見ランダムな順序で返すので、順序が問題になる場合は、
<code>keys</code> メソッドを使う必要があります。
</para>
<para>
The <code>each()</code> operator can be a bit tricky though. You can't add or
delete keys of the hash while you're using it without possibly
skipping or re-processing some pairs after Perl internally rehashes
all of the elements. Additionally, a hash has only one iterator, so if
you use <code>keys</code>, <code>values</code>, or <code>each</code> on the same hash, you can reset
the iterator and mess up your processing. See the <code>each</code> entry in
<link xref='perlfunc'>perlfunc</link> for more details.
</para>
<para>
しかし、<code>each()</code> 演算子は少しトリッキーです。
Perl が内部的に全ての要素を再ハッシュした後にいくつかの組をスキップしたり
再処理したりすることなく、ハッシュの使用中にハッシュのキーを追加したり
削除したりすることは出来ません。
さらに、一つのハッシュは一つのイテレータしか持っていないので、もし同じ
ハッシュに対して <code>keys</code>, <code>values</code>, <code>each</code> を使うと、イテレータを
リセットしてしまって処理が無茶苦茶になってしまいます。
さらなる詳細については <link xref='perlfunc'>perlfunc</link> の <code>each</code> エントリを参照してください。
</para>
</sect2>
<sect2>
<title>What happens if I add or remove keys from a hash while iterating over it?</title>
<para>
(ハッシュに対して反復操作を行っているときにキーの追加や削除をすると何が起きますか?)
</para>
<para>
(contributed by brian d foy)
</para>
<para>
(brian d foy によって寄贈されました)
</para>
<para>
The easy answer is &quot;Don't do that!&quot;
</para>
<para>
簡単な答えは:「そんなことをするな！」
</para>
<para>
If you iterate through the hash with each(), you can delete the key
most recently returned without worrying about it.  If you delete or add
other keys, the iterator may skip or double up on them since perl
may rearrange the hash table.  See the
entry for <code>each()</code> in <link xref='perlfunc'>perlfunc</link>.
</para>
<para>
If you iterate through the hash with each(), you can delete the key
most recently returned without worrying about it.  If you delete or add
other keys, the iterator may skip or double up on them since perl
may rearrange the hash table.
<link xref='perlfunc'>perlfunc</link> の <code>each()</code> のエントリを参照してください。
</para>
</sect2>
<sect2>
<title>How do I look up a hash element by value?</title>
<para>
(ハッシュの要素をその値で検索するには?)
</para>
<para>
Create a reverse hash:
</para>
<para>
リバースハッシュを作成します:
</para>
<verbatim><![CDATA[
%by_value = reverse %by_key;
$key = $by_value{$value};
]]></verbatim>
<para>
That's not particularly efficient.  It would be more space-efficient
to use:
</para>
<para>
これは特に効率がよいものではありません。
空間を効率よく使うにはこうします:
</para>
<verbatim><![CDATA[
while (($key, $value) = each %by_key) {
	$by_value{$value} = $key;
    }
]]></verbatim>
<para>
If your hash could have repeated values, the methods above will only find
one of the associated keys.   This may or may not worry you.  If it does
worry you, you can always reverse the hash into a hash of arrays instead:
</para>
<para>
ハッシュに同じ値がある場合には、このメソッドは最初に見つかったキーだけを
見つけだします。
あなたはこれを気にするかも知れませんし、気にしないかもしれません。
もし気にするのなら、いつでもハッシュの代わりに配列のハッシュを
使うことができます:
</para>
<verbatim><![CDATA[
while (($key, $value) = each %by_key) {
	 push @{$key_list_by_value{$value}}, $key;
	}
]]></verbatim>
</sect2>
<sect2>
<title>How can I know how many entries are in a hash?</title>
<para>
(ハッシュにどれくらいの要素があるのを知るには?)
</para>
<para>
If you mean how many keys, then all you have to do is
use the keys() function in a scalar context:
</para>
<para>
どのくらいのキーがあるのかという事なら、keys()関数をスカラコンテキストで
使います:
</para>
<verbatim><![CDATA[
$num_keys = keys %hash;
]]></verbatim>
<para>
The keys() function also resets the iterator, which means that you may
see strange results if you use this between uses of other hash operators
such as each().
</para>
<para>
keys() 関数も反復動作を初期化するので、
which means that you may
see strange results if you use this between uses of other hash operators
such as each().
</para>
</sect2>
<sect2>
<title>How do I sort a hash (optionally by value instead of key)?</title>
<para>
(ハッシュを(キーではなく値で)ソートするには?)
</para>
<para>
(contributed by brian d foy)
</para>
<para>
(brian d foy によって寄贈されました)
</para>
<para>
To sort a hash, start with the keys. In this example, we give the list of
keys to the sort function which then compares them ASCIIbetically (which
might be affected by your locale settings). The output list has the keys
in ASCIIbetical order. Once we have the keys, we can go through them to
create a report which lists the keys in ASCIIbetical order.
</para>
<para>
ハッシュをソートするために、キーから始めます。
この例では、キーのリストをソート関数に渡して、それから ASCII 順で比較します
(ロケール設定の影響を受けるかもしれません)。
出力リストは ASCII 順のキーのリストです。
キーを得たら、ASCII 順にキーを並べたレポートを作成します。
</para>
<verbatim><![CDATA[
my @keys = sort { $a cmp $b } keys %hash;
]]></verbatim>
<verbatim><![CDATA[
foreach my $key ( @keys )
	{
	printf "%-20s %6d\n", $key, $hash{$value};
	}
]]></verbatim>
<para>
We could get more fancy in the <code>sort()</code> block though. Instead of
comparing the keys, we can compute a value with them and use that
value as the comparison.
</para>
<para>
しかし、<code>sort()</code> ブロックでもっと面白いことができます。
キーを比較する代わりに、これらの値を計算してその値を比較に使います。
</para>
<para>
For instance, to make our report order case-insensitive, we use
the <code>\L</code> sequence in a double-quoted string to make everything
lowercase. The <code>sort()</code> block then compares the lowercased
values to determine in which order to put the keys.
</para>
<para>
例えば、大文字小文字を無視した順序のレポートを作るには、全てを小文字に
するためにダブルクォートされた文字列の中で <code>\L</code> シーケンスが使えます。
それから <code>sort()</code> ブロックがキーを出力する順番を決定するために小文字化された
値を比較します。
</para>
<verbatim><![CDATA[
my @keys = sort { "\L$a" cmp "\L$b" } keys %hash;
]]></verbatim>
<para>
Note: if the computation is expensive or the hash has many elements,
you may want to look at the Schwartzian Transform to cache the
computation results.
</para>
<para>
注意: 計算が高くつくものであったり、ハッシュがたくさんの要素を持っている
場合、計算結果をキャッシュするためにシュワルツ変換を使いたいかもしれません。
</para>
<para>
If we want to sort by the hash value instead, we use the hash key
to look it up. We still get out a list of keys, but this time they
are ordered by their value.
</para>
<para>
もし代わりにハッシュの値でソートしたいなら、それを探すためにハッシュキーを
使います。
やはりキーのリストを使いますが、今度はその値でソートします。
</para>
<verbatim><![CDATA[
my @keys = sort { $hash{$a} <=> $hash{$b} } keys %hash;
]]></verbatim>
<para>
From there we can get more complex. If the hash values are the same,
we can provide a secondary sort on the hash key.
</para>
<para>
ここから、より複雑なものにできます。
ハッシュ値が同じ場合は、ハッシュキーによる第二段階のソートを提供できます。
</para>
<verbatim><![CDATA[
my @keys = sort {
	$hash{$a} <=> $hash{$b}
		or
	"\L$a" cmp "\L$b"
	} keys %hash;
]]></verbatim>
</sect2>
<sect2>
<title>How can I always keep my hash sorted?
<index>hash tie sort DB_File Tie::IxHash</index></title>
<para>
(私のハッシュを常にソートされた状態にしておくには?)
</para>
<para>
You can look into using the <code>DB_File</code> module and <code>tie()</code> using the
<code>$DB_BTREE</code> hash bindings as documented in {tag:link xref='DB_File/&quot;In Memory
Databases&quot;'}DB_File/&quot;In Memory
Databases&quot;</link>. The <code>Tie::IxHash</code> module from CPAN might also be
instructive. Although this does keep your hash sorted, you might not
like the slow down you suffer from the tie interface. Are you sure you
need to do this? :)
</para>
<para>
<link xref='DB_File#In_Memory_Databases'>DB_File/&quot;In Memory Databases&quot;</link> にあるように、<code>DB_File</code> モジュールと
<code>tie()</code> を使った、$DB_BTREE ハッシュ束縛を使うことができます。
CPAN の <code>Tie::IxHash</code> モジュールも有益かもしれません。
これによりハッシュはソートされた状態のままになりますが、tie
インターフェースによって被る速度低下を気に入らないかもしれません。
あなたは本当にこれが必要ですか? :)
</para>
</sect2>
<sect2>
<title>What's the difference between &quot;delete&quot; and &quot;undef&quot; with hashes?</title>
<para>
(ハッシュに対する &quot;delete&quot; と &quot;undef&quot;との間の違いは?)
</para>
<para>
Hashes contain pairs of scalars: the first is the key, the
second is the value.  The key will be coerced to a string,
although the value can be any kind of scalar: string,
number, or reference.  If a key <code>$key</code> is present in
%hash, <code>exists($hash{$key})</code> will return true.  The value
for a given key can be <code>undef</code>, in which case
<code>$hash{$key}</code> will be <code>undef</code> while <code>exists $hash{$key}</code>
will return true.  This corresponds to (<code>$key</code>, <code>undef</code>)
being in the hash.
</para>
<para>
ハッシュはスカラのペアからなります: 最初のスカラがキーで、
二番目のスカラが値です。
キーは文字列、数値、リファレンスのいずれの種類のスカラであっても
強制的に文字列にされます。
%hash の中に <code>$key</code> というキーが既にあれば、<code>exists($hash{$key})</code> は
真を返します。
与えられたキーに対する値は <code>undef</code> とすることができます。
これは <code>$hash{$key}</code> を <code>undef</code> にして、<code>exists $hash{$key}</code> が真を
返すという状態です。
これは (<code>$key</code>, <code>undef</code>)がハッシュに存在しているということを示しています。
</para>
<para>
Pictures help...  here's the <code>%hash</code> table:
</para>
<para>
図が助けになるでしょう。
以下は <code>%hash</code> のテーブルです:
</para>
<verbatim><![CDATA[
keys  values
	+------+------+
	|  a   |  3   |
	|  x   |  7   |
	|  d   |  0   |
	|  e   |  2   |
	+------+------+
]]></verbatim>
<para>
And these conditions hold
</para>
<para>
そしてこれらが保持している状態はこうです:
</para>
<verbatim><![CDATA[
$hash{'a'}                       is true
$hash{'d'}                       is false
defined $hash{'d'}               is true
defined $hash{'a'}               is true
exists $hash{'a'}                is true (Perl 5 only)
grep ($_ eq 'a', keys %hash)     is true
]]></verbatim>
<para>
If you now say
</para>
<para>
ここで
</para>
<verbatim><![CDATA[
undef $hash{'a'}
]]></verbatim>
<para>
your table now reads:
</para>
<para>
とすると、テーブルはこうなります:
</para>
<verbatim><![CDATA[
keys  values
	+------+------+
	|  a   | undef|
	|  x   |  7   |
	|  d   |  0   |
	|  e   |  2   |
	+------+------+
]]></verbatim>
<para>
and these conditions now hold; changes in caps:
</para>
<para>
そしてその状態は以下のようになります。
大文字になっているのが変わった場所です:
</para>
<verbatim><![CDATA[
$hash{'a'}                       is FALSE
$hash{'d'}                       is false
defined $hash{'d'}               is true
defined $hash{'a'}               is FALSE
exists $hash{'a'}                is true (Perl 5 only)
grep ($_ eq 'a', keys %hash)     is true
]]></verbatim>
<para>
Notice the last two: you have an undef value, but a defined key!
</para>
<para>
最後の二つに注目してください: あなたは undef 値を保持していますが、
キーは define されているのです!
</para>
<para>
Now, consider this:
</para>
<para>
さて、こんどは以下の例を考えてみましょう:
</para>
<verbatim><![CDATA[
delete $hash{'a'}
]]></verbatim>
<para>
your table now reads:
</para>
<para>
テーブルはこうなります:
</para>
<verbatim><![CDATA[
keys  values
	+------+------+
	|  x   |  7   |
	|  d   |  0   |
	|  e   |  2   |
	+------+------+
]]></verbatim>
<para>
and these conditions now hold; changes in caps:
</para>
<para>
そしてその状態はこうです。大文字の部分が変わったところです:
</para>
<verbatim><![CDATA[
$hash{'a'}                       is false
$hash{'d'}                       is false
defined $hash{'d'}               is true
defined $hash{'a'}               is false
exists $hash{'a'}                is FALSE (Perl 5 only)
grep ($_ eq 'a', keys %hash)     is FALSE
]]></verbatim>
<para>
See, the whole entry is gone!
</para>
<para>
ほら、エントリが丸ごとなくなっていまいました!
</para>
</sect2>
<sect2>
<title>Why don't my tied hashes make the defined/exists distinction?</title>
<para>
(なぜわたしの tie されたハッシュは defined と exists を区別しないのでしょうか?)
</para>
<para>
This depends on the tied hash's implementation of EXISTS().
For example, there isn't the concept of undef with hashes
that are tied to DBM* files. It also means that exists() and
defined() do the same thing with a DBM* file, and what they
end up doing is not what they do with ordinary hashes.
</para>
<para>
これは tie されたハッシュの EXISTS() の実装に依存します。
たとえば、DBM* ファイルに tie されたハッシュには undef という考え方はありません。
これはまた DBM* ファイルにとっては exists() と defined() とは同じことであり、
そういったものに対して行っていることは
通常のハッシュに対して行っていることとは違うのだということなのです。
</para>
</sect2>
<sect2>
<title>How do I reset an each() operation part-way through?</title>
<para>
(each() 操作の途中でリセットしてしまうには?)
</para>
<para>
(contributed by brian d foy)
</para>
<para>
(brian d foy によって寄贈されました)
</para>
<para>
You can use the <code>keys</code> or <code>values</code> functions to reset <code>each</code>. To
simply reset the iterator used by <code>each</code> without doing anything else,
use one of them in void context:
</para>
<para>
<code>each</code> をリセットするために <code>keys</code> 関数か <code>values</code> 関数が使えます。
他に何もせずに単に <code>each</code> で使われているイテレータをリセットするには、
これらの一つを無効コンテキストで使います:
</para>
<verbatim><![CDATA[
keys %hash; # resets iterator, nothing else.
values %hash; # resets iterator, nothing else.
]]></verbatim>
<para>
See the documentation for <code>each</code> in <link xref='perlfunc'>perlfunc</link>.
</para>
<para>
<link xref='perlfunc'>perlfunc</link> にある <code>each</code> の説明を参照してください。
</para>
</sect2>
<sect2>
<title>How can I get the unique keys from two hashes?</title>
<para>
(二つのハッシュからユニークなキーを取りだすには?)
</para>
<para>
First you extract the keys from the hashes into lists, then solve
the &quot;removing duplicates&quot; problem described above.  For example:
</para>
<para>
まず最初にハッシュからキーを取りだして、それをリストに格納します。
そして、先に説明した「重複の削除」問題の解決を行います。例:
</para>
<verbatim><![CDATA[
%seen = ();
for $element (keys(%foo), keys(%bar)) {
	$seen{$element}++;
	}
@uniq = keys %seen;
]]></verbatim>
<para>
Or more succinctly:
</para>
<para>
あるいはもっと簡潔に:
</para>
<verbatim><![CDATA[
@uniq = keys %{{%foo,%bar}};
]]></verbatim>
<para>
Or if you really want to save space:
</para>
<para>
もし本当にメモリ空間を節約したいのなら:
</para>
<verbatim><![CDATA[
%seen = ();
while (defined ($key = each %foo)) {
	$seen{$key}++;
}
while (defined ($key = each %bar)) {
	$seen{$key}++;
}
@uniq = keys %seen;
]]></verbatim>
</sect2>
<sect2>
<title>How can I store a multidimensional array in a DBM file?</title>
<para>
(DBM ファイルに多次元配列を格納するには?)
</para>
<para>
Either stringify the structure yourself (no fun), or else
get the MLDBM (which uses Data::Dumper) module from CPAN and layer
it on top of either DB_File or GDBM_File.
</para>
<para>
自分自身で構造を文字列化する(うれしくないですね)か、MLDBM モジュール
(Data::Dumper を使います)を
CPAN から取ってきて、DB_File か GDBM_File のいずれかのトップレイヤーにします。
</para>
</sect2>
<sect2>
<title>How can I make my hash remember the order I put elements into it?</title>
<para>
(わたしのハッシュが格納した順番を覚えておくようにするには?)
</para>
<para>
Use the <code>Tie::IxHash</code> from CPAN.
</para>
<para>
CPAN にある <code>Tie::IxHash</code> を使います。
</para>
<verbatim><![CDATA[
use Tie::IxHash;
]]></verbatim>
<verbatim><![CDATA[
tie my %myhash, 'Tie::IxHash';
]]></verbatim>
<verbatim><![CDATA[
for (my $i=0; $i<20; $i++) {
	$myhash{$i} = 2*$i;
	}
]]></verbatim>
<verbatim><![CDATA[
my @keys = keys %myhash;
# @keys = (0,1,2,3,...)
]]></verbatim>
</sect2>
<sect2>
<title>Why does passing a subroutine an undefined element in a hash create it?</title>
<para>
(なぜあるハッシュの未定義要素をサブルーチンに渡すとそれを作成するのでしょうか?)
</para>
<para>
If you say something like:
</para>
<para>
以下のようなことをしようとすると:
</para>
<verbatim><![CDATA[
somefunc($hash{"nonesuch key here"});
]]></verbatim>
<para>
Then that element &quot;autovivifies&quot;; that is, it springs into existence
whether you store something there or not.  That's because functions
get scalars passed in by reference.  If somefunc() modifies <code>$_[0]</code>,
it has to be ready to write it back into the caller's version.
</para>
<para>
この要素は新たに生みだされます(&quot;autovivifies&quot;);
これはつまり、あなたがそこに何かを格納するため(実際に格納することがなくても)に
作り出されるのです。
これは関数が渡されたスカラをリファレンスで受け取るからです。
somefunc() が <code>$_[0]</code> を変更するのなら、
呼び出し元にそれを反映させるために書き込みができるように
なっていなければなりません。
</para>
<para>
This has been fixed as of Perl5.004.
</para>
<para>
これは Perl5.004 で修正されました。
</para>
<para>
Normally, merely accessing a key's value for a nonexistent key does
<emphasis>not</emphasis> cause that key to be forever there.  This is different than
awk's behavior.
</para>
<para>
通常は、存在していないキーに対するアクセスは、そのキーを生成する
ようなことは <strong>ありません</strong>。
これは awk の振る舞いとは異なります．
</para>
</sect2>
<sect2>
<title>How can I make the Perl equivalent of a C structure/C++ class/hash or array of hashes or arrays?</title>
<para>
(C の構造体/C++ のクラスのハッシュ、配列のハッシュ、配列と等価なものを Perl で作成するには?)
</para>
<para>
Usually a hash ref, perhaps like this:
</para>
<para>
通常はハッシュのリファレンスを使います。
多分以下のようになるでしょう:
</para>
<verbatim><![CDATA[
$record = {
	NAME   => "Jason",
	EMPNO  => 132,
	TITLE  => "deputy peon",
	AGE    => 23,
	SALARY => 37_000,
	PALS   => [ "Norbert", "Rhys", "Phineas"],
};
]]></verbatim>
<para>
References are documented in <link xref='perlref'>perlref</link> and the upcoming <link xref='perlreftut'>perlreftut</link>.
Examples of complex data structures are given in <link xref='perldsc'>perldsc</link> and
<link xref='perllol'>perllol</link>.  Examples of structures and object-oriented classes are
in <link xref='perltoot'>perltoot</link>.
</para>
<para>
リファレンスは <link xref='perlref'>perlref</link> と <link xref='perlreftut'>perlreftut</link> に説明があります。
複雑なデータ構造の例が <link xref='perldesc'>perldesc</link> と <link xref='perllol'>perllol</link> にあります。
構造体とオブジェクト指向クラスの例が <link xref='perltoot'>perltoot</link> にあります。
</para>
</sect2>
<sect2>
<title>How can I use a reference as a hash key?</title>
<para>
(ハッシュのキーとしてリファレンスを使うには?)
</para>
<para>
(contributed by brian d foy)
</para>
<para>
(brian d foy によって寄贈されました)
</para>
<para>
Hash keys are strings, so you can't really use a reference as the key.
When you try to do that, perl turns the reference into its stringified
form (for instance, <code>HASH(0xDEADBEEF)</code>). From there you can't get
back the reference from the stringified form, at least without doing
some extra work on your own. Also remember that hash keys must be
unique, but two different variables can store the same reference (and
those variables can change later).
</para>
<para>
ハッシュキーは文字列なので、実際にリファレンスをキーとして使うことは
できません。
もしそうしようとすると、perl はリファレンスを(例えば <code>HASH(0xDEADBEEF)</code> の
形に)文字列化 します。
少なくとも自分自身で追加の作業をしない限り、文字列化された形から
リファレンスを得ることはできません。
ハッシュキーはユニークでなければなりませんが、二つの異なる変数が
同じリファレンスを保管できる(そしてこれらの変数は後で変更できる)ことも
忘れないでください。
</para>
<para>
The <code>Tie::RefHash</code> module, which is distributed with perl, might be
what you want. It handles that extra work.
</para>
<para>
perl と共に配布されている <code>Tie::RefHash</code> モジュールが、あなたの求めている
ものかもしれません。
これは追加の作業を扱います。
</para>
</sect2>
</sect1>
<sect1>
<title>Data: Misc</title>
<para>
(データ:その他)
</para>
<sect2>
<title>How do I handle binary data correctly?</title>
<para>
(バイナリデータを正しく扱うには?)
</para>
<para>
Perl is binary clean, so it can handle binary data just fine.
On Windows or DOS, however, you have to use <code>binmode</code> for binary
files to avoid conversions for line endings. In general, you should
use <code>binmode</code> any time you want to work with binary data.
</para>
<para>
Perl はバイナリクリーンですから、バイナリデータをうまく扱えます。
しかし、 Windows や DOS では、バイナリファイルに対して行末の変換を避けるために、
<code>binmode</code> を使う必要があります。
一般的には、バイナリデータを扱いたいときはいつでも <code>binmode</code> を
使うべきです。
</para>
<para>
Also see <link xref='perlfunc#binmode'>perlfunc/&quot;binmode&quot;</link> or <link xref='perlopentut'>perlopentut</link>.
</para>
<para>
<link xref='perlfunc#binmode'>perlfunc/&quot;binmode&quot;</link> と <link xref='perlopentut'>perlopentut</link> も参照してください。
</para>
<para>
If you're concerned about 8-bit textual data then see <link xref='perllocale'>perllocale</link>.
If you want to deal with multibyte characters, however, there are
some gotchas.  See the section on Regular Expressions.
</para>
<para>
もし 8 ビットテキストデータについて考えているのであれば、<link xref='perllocale'>perllocale</link> を
参照してください。
ただしマルチバイトキャラクターを扱いたいと考えているなら、幾つかの
罠(gotchas)があります。
正規表現のセクションを参照してください。
</para>
</sect2>
<sect2>
<title>How do I determine whether a scalar is a number/whole/integer/float?</title>
<para>
(あるスカラ値が数値/整数/浮動小数点数かどうかを決定するには?)
</para>
<para>
Assuming that you don't care about IEEE notations like &quot;NaN&quot; or
&quot;Infinity&quot;, you probably just want to use a regular expression.
</para>
<para>
&quot;NaN&quot; や &quot;Infinity&quot; のような IEEE 表記については気にしないと仮定すると、
正規表現を使って行うことができます。
</para>
<verbatim><![CDATA[
if (/\D/)            { print "has nondigits\n" }
if (/^\d+$/)         { print "is a whole number\n" }
if (/^-?\d+$/)       { print "is an integer\n" }
if (/^[+-]?\d+$/)    { print "is a +/- integer\n" }
if (/^-?\d+\.?\d*$/) { print "is a real number\n" }
if (/^-?(?:\d+(?:\.\d*)?|\.\d+)$/) { print "is a decimal number\n" }
if (/^([+-]?)(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?$/)
		{ print "a C float\n" }
]]></verbatim>
<para>
There are also some commonly used modules for the task.
<link xref='Scalar::Util'>Scalar::Util</link> (distributed with 5.8) provides access to perl's
internal function <code>looks_like_number</code> for determining whether a
variable looks like a number.  <link xref='Data::Types'>Data::Types</link> exports functions that
validate data types using both the above and other regular
expressions. Thirdly, there is <code>Regexp::Common</code> which has regular
expressions to match various types of numbers. Those three modules are
available from the CPAN.
</para>
<para>
この作業のためによく使われるいくつかのモジュールがあります。
<link xref='Scalar::Util'>Scalar::Util</link> (5.8 と共に配布されています) は、変数が数値に見えるか
どうかを決定するために perl の内部関数 <code>looks_like_number</code> へのアクセスを
提供します。
<link xref='Data::Types'>Data::Types</link> は上記のものとその他の正規表現の両方を使ってデータ型の
バリデートを行う関数をエクスポートします。
3 つめとして、<code>Regexp::Common</code> には様々な種類の数値にマッチングする
正規表現があります。
これら 3 つのモジュールは CPAN にあります。
</para>
<para>
If you're on a POSIX system, Perl supports the <code>POSIX::strtod</code>
function.  Its semantics are somewhat cumbersome, so here's a
<code>getnum</code> wrapper function for more convenient access.  This function
takes a string and returns the number it found, or <code>undef</code> for input
that isn't a C float.  The <code>is_numeric</code> function is a front end to
<code>getnum</code> if you just want to say, &quot;Is this a float?&quot;
</para>
<para>
POSIXシステムを使っているのなら、Perlは <code>POSIX::strtod</code>
関数をサポートしています。
そのセマンティックは扱いにくいもので、もっと便利にアクセスするための
<code>getnum</code> 関数を以下に例示します。
この関数は文字列を引数に取り、その文字列中で見つかった数字列に対応する
数値を返し、入力がCの小数点表記にあわないものであれば <code>undef</code> を返します。
<code>is_numeric</code> 関数は“これは数値か?”ということを知りたい場合に
<code>getnum</code> のフロントエンドとなります。
</para>
<verbatim><![CDATA[
sub getnum {
	use POSIX qw(strtod);
	my $str = shift;
	$str =~ s/^\s+//;
	$str =~ s/\s+$//;
	$! = 0;
	my($num, $unparsed) = strtod($str);
	if (($str eq '') || ($unparsed != 0) || $!) {
			return undef;
		}
	else {
		return $num;
		}
	}
]]></verbatim>
<verbatim><![CDATA[
sub is_numeric { defined getnum($_[0]) }
]]></verbatim>
<para>
Or you could check out the <link xref='String::Scanf'>String::Scanf</link> module on the CPAN
instead. The <code>POSIX</code> module (part of the standard Perl distribution)
provides the <code>strtod</code> and <code>strtol</code> for converting strings to double
and longs, respectively.
</para>
<para>
あるいは、CPAN にある <link xref='String::Scanf'>String::Scanf</link> モジュールをチェックしてみてください。
<code>POSIX</code> モジュール(標準 Perl 配布キットの一部です)は文字列から
倍精度浮動小数点数や長整数への変換を適切に行う <code>strtod</code> と <code>strtol</code> を
提供しています。
</para>
</sect2>
<sect2>
<title>How do I keep persistent data across program calls?</title>
<para>
(プログラムの呼び出しの間に、データ構造を永続的に保持するには?)
</para>
<para>
For some specific applications, you can use one of the DBM modules.
See <link xref='AnyDBM_File'>AnyDBM_File</link>.  More generically, you should consult the <code>FreezeThaw</code>
or <code>Storable</code> modules from CPAN.  Starting from Perl 5.8 <code>Storable</code> is part
of the standard distribution.  Here's one example using <code>Storable</code>'s <code>store</code>
and <code>retrieve</code> functions:
</para>
<para>
一部の特定のアプリケーションでは、DBM モジュールの一つを使うことができます。
<link xref='AnyDBM_File'>AnyDBM_File</link> を参照してください。
より一般的には、CPAN にある <code>FreezeThaw</code>, <code>Storable</code> といった
モジュールをあたってみるべきでしょう。
Perl 5.8 から、<code>Storable</code> は標準配布の一部となりました。
以下に <code>Storable</code> の <code>store</code> と <code>retrieve</code> を使った例を挙げます:
</para>
<verbatim><![CDATA[
use Storable;
store(\%hash, "filename");
]]></verbatim>
<verbatim><![CDATA[
# later on...
$href = retrieve("filename");        # by ref
%hash = %{ retrieve("filename") };   # direct to hash
]]></verbatim>
</sect2>
<sect2>
<title>How do I print out or copy a recursive data structure?</title>
<para>
(再帰的なデータ構造を出力したりコピーするには?)
</para>
<para>
The <code>Data::Dumper</code> module on CPAN (or the 5.005 release of Perl) is great
for printing out data structures.  The <code>Storable</code> module on CPAN (or the
5.8 release of Perl), provides a function called <code>dclone</code> that recursively
copies its argument.
</para>
<para>
CPAN にある <code>Data::Dumper</code> モジュール(5.005 以降では Perl のリリースに
含まれています)はデータ構造を出力するのに向いています。
CPAN にある <code>Storable</code> モジュール(5.8 以降では Perl のリリースに
含まれています)はその引数を再帰的にコピーする
<code>dclone</code> という関数を提供しています。
</para>
<verbatim><![CDATA[
use Storable qw(dclone);
$r2 = dclone($r1);
]]></verbatim>
<para>
Where <code>$r1</code> can be a reference to any kind of data structure you'd like.
It will be deeply copied.  Because <code>dclone</code> takes and returns references,
you'd have to add extra punctuation if you had a hash of arrays that
you wanted to copy.
</para>
<para>
ここで <code>$r1</code> にはあなたの望むデータ構造のリファレンスを置くことができます。
これは深くコピー(deeply copied)されます。
<code>dclone</code> はリファレンスを取り
リファレンスを返すので、コピーしたいものが配列のハッシュであったりした
場合には余計なpunctuationが必要となるでしょう。
</para>
<verbatim><![CDATA[
%newhash = %{ dclone(\%oldhash) };
]]></verbatim>
</sect2>
<sect2>
<title>How do I define methods for every class/object?</title>
<para>
(すべてのクラス/オブジェクトのためのメソッドを定義するには?)
</para>
<para>
Use the <code>UNIVERSAL</code> class (see <link xref='UNIVERSAL'>UNIVERSAL</link>).
</para>
<para>
<code>UNIVERSAL</code> クラス (<link xref='UNIVERSAL'>UNIVERSAL</link>) を参照)を使います。
</para>
</sect2>
<sect2>
<title>How do I verify a credit card checksum?</title>
<para>
(クレジットカードのチェックサムを検査するには?)
</para>
<para>
Get the <code>Business::CreditCard</code> module from CPAN.
</para>
<para>
CPAN から <code>Business::CreditCard</code> モジュールを入手してください。
</para>
</sect2>
<sect2>
<title>How do I pack arrays of doubles or floats for XS code?</title>
<para>
(XSプログラムのために倍精度実数や単精度実数の配列を pack するには?)
</para>
<para>
The kgbpack.c code in the <code>PGPLOT</code> module on CPAN does just this.
If you're doing a lot of float or double processing, consider using
the <code>PDL</code> module from CPAN instead--it makes number-crunching easy.
</para>
<para>
CPAN にある <code>PGPLOT</code> モジュールにある kgbpack.c というものがそれをします。
倍精度実数や単精度実数を大量に扱うのであれば、CPAN にある
<code>PDL</code> モジュールを使うことを考えてみるとよいでしょう。
これは number-crunching を簡単にしてくれます。
</para>
</sect2>
</sect1>
<sect1>
<title>REVISION</title>
<para>
Revision: $Revision: 10394 $
</para>
<para>
Date: $Date: 2007-12-09 18:47:15 +0100 (Sun, 09 Dec 2007) $
</para>
<para>
See <link xref='perlfaq'>perlfaq</link> for source control details and availability.
</para>
</sect1>
<sect1>
<title>AUTHOR AND COPYRIGHT</title>
<para>
Copyright (c) 1997-2007 Tom Christiansen, Nathan Torkington, and
other authors as noted. All rights reserved.
</para>
<para>
This documentation is free; you can redistribute it and/or modify it
under the same terms as Perl itself.
</para>
<para>
Irrespective of its distribution, all code examples in this file
are hereby placed into the public domain.  You are permitted and
encouraged to use this code in your own programs for fun
or for profit as you see fit.  A simple comment in the code giving
credit would be courteous but is not required.
</para>
</sect1>
</pod>
