LEARING PERL - 4번째 학습

이동욱

2021/12/08

Categories:

FOR 반복문


#!/usr/bin/perl

foreach $rock (qw/ bedrock slate lava /) {
    print "one rock is $rock.\n";
}
#!/usr/bin/perl

@rocks = qw/ bedrock slate lava /;

foreach $rock (@rocks) {
    $rock = "\t$rock";
    $rock .= "\n";
}
print "The rocks are:\n", @rocks;
#!/usr/bin/perl

$rock = 'shale';

@rocks = qw" bedrock slate lava ";

foreach $rock (@rocks) {
  print "$rock\n";
}

print "rock is still $rock\n"; # 'rocks is still shale'

$_ 변수


#!/usr/bin/perl

foreach (1..10) {
  print "I can count to $_ !\n";
}
#!/usr/bin/perl

foreach (1..10) {
  print "I can count to $_ !\n";
}

$_ = "Yabba dabba doo\n";
print; # 'Yadda badda doo'

reverse 연산자


#!/usr/bin/perl

@fred = 6..10;
print "@fred\n";
@barney = reverse(@fred);
print "@fred\n";
@wilma = reverse 6..10;
print "@wilma\n";
@fred = reverse @fred;
print "@fred\n";

sort 연산자


#!/usr/bin/perl

@rocks = qw/ bedrock slate rubble granite /;
print "@rocks\n"; # bedrock slate rubble granite

@sorted = sort(@rocks);
print "@sorted\n"; # bedrock granite rubble slate
@back = reverse sort @rocks;
print "@back\n"; # slate rubble granite bedrock
@rocks = sort @rocks;
print "@rocks\n"; # bedrock granite rubble slate
@numbers = sort 97..102; # 100 101 102 97 98 99
print "@numbers\n";

each 연산자


#!/usr/bin/perl

@rocks = qw/ bedrock slate rubble granite /;
while (($index, $value) = each @rocks) {
  print "$index: $value\n";
}

# 결과
0: bedrock
1: slate
2: rubble
3: granite

스칼라 값과 리스트 값은 문맥에 따라서 달라진다


@people = qw (fred barney betty);
@sorted = sort @people; # list context: barney, betty, fred
$number = 42 + @people; # 42 + 3 = 45
/usr/bin/perl

@backwards = reverse qw/ yadda dabba doo/;
print "@backwards\n";
$backwards = reverse qw/ yabba dabba doo /;
print "$backwards\n";

== result ==
doo dabba yadda
oodabbadabbay
$fred = something; # 스칼라
@pebbles = something; # 리스트
($wilma, $betty) = something; # 리스트
($dino) = something # 리스트
@fred = 6 * 7 # list (42)
@barney = "hello" . ' ' . "world";

@wilma = undef # list (undef)
@betty = (  ); # empty array
!/usr/bin/perl

@rocks = qw( talc quartz jade obsidian );

print "How many rocks do you have?\n";
print "I have ", @rocks, " rocks!\n";
print "I hvae ", scalar @rocks, " rocks!\n";

=== result ===
How many rocks do you have?
I have talcquartzjadeobsidian rocks!
I hvae 4 rocks!


@lines = <STDIN>;
chomp(@lines);

참고 문헌

>> Home