24
23

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Perlで配列要素と一緒に要素番号を取得する

Last updated at Posted at 2013-01-29

配列をループで処理するときに、要素と一緒に要素番号も欲しくなることが稀によくあるが、Perlでやる方法を今まで知らなかったのでメモ
PythonのenumerateとかRubyのeach_with_indexのPerl版

with_index.pl
my @a = (10..20);
while(my ($i,$j) = each @a){
    print "$i $j\n";
}
$ perl with_index.pl
0 10
1 11
2 12
3 13
4 14
5 15
6 16
7 17
8 18
9 19
10 20

ただeachするだけでよかった

######追記
コメントで指摘されてる通り、mapで使いたいけど、いい感じの方法が見つからなかった
仕方なく、自分で書いてみた

sub each_with_index {
    my @ret;
    while (my ($i,$j) = each @_) {
        push @ret, [$i, $j];
    }
    return @ret;
}

my @a = (10..20);
print "$_\n" for map { "$_->[0]:  $_->[1]" } each_with_index @a;

Tie変数とかいうのを使ってみた。

{
    package Tie::WithIndex;
    sub TIEARRAY {
        my ($pkg, @array) = @_;
        bless { array => \@array }, $pkg;
    }
    sub FETCH {
        my ($this, $index) = @_;
        return [$index, $this->{array}->[$index]]
    }
    sub FETCHSIZE {
        my ($this, $index) = @_;
        return scalar(@{$this->{array}});
    }
}

tie my @a, 'Tie::WithIndex', (10..20);
print "$_\n" for map { "$_->[0] : $_->[1]" } @a;
24
23
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
24
23

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?