2024/02/13 22:13:39

Perl標準関数: chop

chop

chop VARIABLE

chop( LIST )

Chops off the last character of a string and returns the character chopped. It is much more efficient than "s/.$//s" because it neither scans nor copies the string. If VARIABLE is omitted, chops $_. If VARIABLE is a hash, it chops the hash's values, but not its keys.

You can actually chop anything that's an lvalue, including an assignment.

If you chop a list, each element is chopped. Only the value of the last "chop" is returned.

Note that "chop" returns the last character. To return all but the last character, use "substr($string, 0, -1)".

See also "chomp".

chop 関数は、文字列の末尾を落とし、その落とした文字を返します。 文字列を検索したりコピーしたりしないので、"s/.$//s" よりも効率的です。 VARIABLE が省略されたときは、 $_ を対象とします。 ハッシュの場合は、値が chop の対象となり、キーは chop されません。 リストを渡すと、要素それぞれが chop され、最後に chop された文字だけが返ります。 返り値に最後の文字ではなく、すべての文字列が欲しい場合は、"substr($string, 0, -1)" としましょう。

"chomp" も参考にしてください。

chop サンプルコード

末尾を取り除きます

my $str = "perl";

chop $str; # per

リストを渡すと、各要素が対象になります

my @list = (
    "perl",
    "php",
    "python",
);

my $str = chop @list;

print "$str\n"; # n

print "@list"; # ("per", "ph", "pytho")
サイト内検索