Snippets

sironekotoro Perl入学式 2018 第3回 練習問題 array_ref.pl

Created by sironekotoro
#!/usr/bin/env perl
use strict;
use warnings;

# Perl入学式 2018 第3回 練習問題
# https://github.com/perl-entrance-org/workshop-2018/blob/master/3rd/slide.md
# 練習問題(array_ref.pl)

# animal
#  ├─ dog
#  │    ├─ shiba
#  │    └─ bulldog
#  ├─ cat
#  │    ├─ mike
#  │    └─ abyssinian
#  └─ bird
#        ├─ eagle
#        └─ crow

# 次の処理をする array_ref.pl を作りましょう。
# 1.上記のデータ構造を表す@animalを作ってください。
# 2.その中からeagleを取り出してください。
# 3.余裕があれば、他の要素も取り出してみましょう。

# 1.上記のデータ構造を表す@animalを作ってください
# に従い、配列を作る
my @animal;

# 配列を作り、配列リファレンスをスカラー変数に格納する方法
my @dog = ( 'shiba', 'bulldog' );
my $dog_ref = \@dog;

# 無名配列をスカラー変数に格納する方法
my $cat_ref = [ 'mike', 'abyssinian' ];

# 配列を作る際に、qwショートカットを使った例
my @bird     = qw(eagle crow);
my $bird_ref = \@bird;

# push関数で、配列に配列リファレンスを入れていく
push @animal, $dog_ref;
push @animal, $cat_ref;
push @animal, $bird_ref;

# アロー記法を利用
print $animal[2]->[0], "\n";    # eagle
# アローを省略した記法
print $animal[1][1], "\n";      # abyssinian
# 配列の中の配列リファレンスをデリファレンスし、
# 添え字でアクセスする
print ${ $animal[0] }[0], "\n"; # shiba

Comments (0)

HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.