1
0

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 3 years have passed since last update.

Perlの変数宣言について

Posted at

はじめに

実務でperlのファイルを書くことが多く、今までなんとなくノリで乗り切ってきた部分を実験しながら備忘録として残しておく。

Perlの変数の基本

接頭詞 意味
$ スカラー(数値や文字列などの値)
@ 配列
% ハッシュ

スカラーの宣言

my $a = 1;
printf $a;
# 1

my $b = "test";
printf $b;
# test

配列やハッシュを代入

my $c = (1,2,3,4,5);
printf $c;
# 5 <=要素数

my $d = ("first" => "yamada","last" => "taro");
printf $d;
# taro <= 要素の中身の一つ

リファレンス

my $e = [1,2,3,4,5];
printf $e;
# ARRAY(0x7f907d80b6b8) <= 配列のリファレンス

my $f = {"first" => "yamada","last" => "taro"};
printf $f;
# HASH(0x7fefe080b6b8) <= ハッシュのリファレンス

配列の宣言

my @a = (1,2,3,4,5);
printf @a;
# 1 <=先頭の値が出力される
printf "@a";
# 1 2 3 4 5 配列の中身が出力される

printf @a[2];
# 3 3番目の要素が出力される

printf @a[-1];
# 5 最後の要素が出力される

my $b = @a;
printf $b;
# 5 要素数が出力される

my @c = [1,2,3,4,5];
printf @c;
# ARRAY(0x7fd41700b6b8) <= 配列のリファレンス 但、なんか値取り出せない

ハッシュの宣言

my %a = (first=>"yamada",last=>"taro");
printf %a;
# first 要素の中の一つ

printf "%a"
# %a そのまま出力される

printf %a->{first};
# yamada そのキーの値が出力される

printf %a->{"first"};
# yamada そのキーの値が出力される

my %b = {first=>"yamada",last=>"taro"};
printf %b;
# HASH(0x7f8bc200b6b8) <= ハッシュのリファレンス 但、なんか値取り出せない

リファレンス

配列

my @a = (1,2,3,4,5);
my $b = \@a; #リファレンス
my $b = [1,2,3,4,5]; #リファレンス

printf $b->[3];
# 4 要素の取り出し

printf "@$b"; #デリファレンス
# 1,2,3,4,5 

ハッシュ

my %a = (first=>"yamada",last=>"taro");
my $b = \%a; #リファレンス
my $b = {first=>"yamada",last=>"taro"}; #リファレンス

printf $b->{first};
# 4 要素の取り出し

printf %$b; #デリファレンス
# first 

色々と実験してみて分かったこと

・見た目だけじゃ結構わからない。
・リファレンスを@や%の接頭詞に代入するとなんか中身取り出せなくなるので大人しくスカラー変数に入れといた方が良い。

1
0
0

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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?