본문 바로가기

Script/Perl

12. Reference

Reference
 
참조는 포인터다.
 
포인터에 접근하기 위해서는 ${ } 에 포인터로 사용된 변수를 넣으면 된다.
 
주소를 저장하기 위해서는 역슬래시 \ 를 이용하여 저장한다.
 
모호한 점이 없다면 접근시 {} 를 생략할 수 있다.
 
my $colour = "Indigo";
my $scalarRef = \ $colour ;
 
print $colour ; # "Indigo"
print $scalarRef ; # 주소값이 SCALAR(..) 으로 출력
print ${ $scalarRef } ; # "Indigo"
print $$scalarRef ; # 모호한 점이 없다면 중괄호 생략 가능
 
아래는 배열에 대한 참조인데 결국 포인터라서 -> 를 이용하여 원소에 접근가능하다.
 
my @colours = ( "Red", "Orange" , "Yellow", "Green", "Blue" );
my $arrayRef = \ @colours ;
 
print $colours [0]; # 배열 직접 접근
print ${ $arrayRef } [0]; # 참조를 이용하여 배열에 접근
print $arrayRef ->[0]; # 위와 똑같음
 
아래는 해쉬에 대한 참조인데 결국 포인터라서 -> 를 이용하여 원소에 접근가능하다.
 
my %atomicWeights = ( "Hydrogen" => 1 .008, "Helium" => 4 .003, "Manganese" => 54. 94);
my $hashRef = \ %atomicWeights ;
 
print $atomicWeights {"Helium"}; # 해시 직접 접근
print ${ $hashRef } {"Helium"}; # 참조를 이용하여 해시에 접근
print $hashRef ->{"Helium"}; # 위와 똑같음. 많이 사용되는 형태
 
 
 
자료구조 선언 및 접근법
 
참조를 사용하면 자료구조를 만들 수 있으며 아래와 같이 하나씩 얻어와 접근할 수 있다.
 
my %owner1 = (
    "name" => "Santa Claus" ,
    "DOB" => "1882-12-25" ,
);
 
my %owner2 = (
    "name" => "Mickey Mouse" ,
    "DOB" => "1928-11-18" ,
);
 
my @owners = ( \ %owner1 , \%owner2 );
 
my %account = (
    "number" => "12345678" ,
    "opened" => "2000-01-01" ,
    "owners" => \@owners,
);
 
# 임시 스칼라 변수를 이용하는 방법
my $ownersRef = $account {"owners"};
my $owner1Ref = $ownersRef ->[0];
my $owner2Ref = $ownersRef ->[1];
 
print $owner1Ref ->{"name"}, "\n";
print $owner2Ref ->{"DOB"},  "\n";
print $owner1Ref ->{"name"}, "\n";
print $owner2Ref ->{"DOB"},  "\n";
 
# 중간 과정없이 얻는 방법
print $account {"owners"}->[0]->{"name"}, "\n";
print $account {"owners"}->[0]->{"DOB"}, "\n";
print $account {"owners"}->[1]->{"name"}, "\n";
print $account {"owners"}->[1]->{"DOB"}, "\n";
 
 
 
 
 

'Script > Perl' 카테고리의 다른 글

14. Class  (0) 2020.01.21
13. Sub Routine  (0) 2020.01.21
11. Context  (0) 2020.01.21
10. conditional sentence  (0) 2020.01.21
09. string  (0) 2020.01.21