기본
Hello World
#!/usr/bin/perl use strict; use warnings; print "Hello, World!\n"; say "Hello, World!"; # with use feature 'say';
Perl 실행
perl script.pl # run a file perl -e 'print "hi\n"' # run inline perl -ne 'print' file # process file line by line
주석 및 문서
# single-line comment =pod Multi-line POD documentation =cut
변수
시질
$scalar단일 값 (문자열, 숫자, 레퍼런스)
@array스칼라의 정렬된 목록
%hash키-값 쌍
$array[0]단일 배열 원소 접근 (스칼라 컨텍스트)
$hash{key}단일 해시 값 접근 (스칼라 컨텍스트)
스칼라 변수
my $name = "Perl"; # string my $version = 5.40; # number my $count = 42; # integer my $undef; # undefined (undef) my $combined = "$name v$version"; # interpolation
컨텍스트
my @arr = (1, 2, 3); my $count = @arr; # scalar context: 3 my @copy = @arr; # list context: (1, 2, 3) my $len = scalar @arr; # force scalar context
특수 변수
$_기본 변수 (topic)
@_서브루틴 인수
$!시스템 오류 메시지
$@eval 오류
$0프로그램 이름
@ARGV명령행 인수
%ENV환경 변수
연산자
비교 연산자
==, !=, <, >, <=, >=숫자 비교
eq, ne, lt, gt, le, ge문자열 비교
<=>숫자 우주선 연산자 (-1, 0, 1 반환)
cmp문자열 우주선 연산자
=~정규식 매칭 / 바인딩
!~정규식 부정 매칭
문자열 연산자
my $full = "Hello" . " " . "World"; # concatenation my $line = "-" x 40; # repetition my $len = length($full); # 11
논리 연산자
&& / and논리 AND (낮은 우선순위: and)
|| / or논리 OR (낮은 우선순위: or)
// 정의-or (정의된 경우 왼쪽 반환)
! / not논리 NOT
? :삼항 조건
제어 흐름
조건문
if ($x > 0) { print "positive\n"; } elsif ($x == 0) { print "zero\n"; } else { print "negative\n"; } print "yes\n" if $condition; # postfix if print "no\n" unless $condition; # postfix unless
반복문
for my $i (0..9) { print "$i\n"; } foreach my $item (@array) { print "$item\n"; } while ($line = ) { chomp $line; } until ($done) { last if check(); }
반복문 제어
next다음 반복으로 건너뜀 (continue 유사)
last반복문 종료 (break 유사)
redo현재 반복 재시작
next LABEL레이블된 반복문의 다음 반복으로
last LABEL레이블된 반복문 종료
Given / When
use feature 'switch'; given ($status) { when ("ok") { say "success"; } when ("error") { say "failed"; } default { say "unknown"; } }
서브루틴
기본 서브루틴
sub greet { my ($name) = @_; return "Hello, $name!"; } my $msg = greet("Alice");
기본값 및 이름 있는 파라미터
sub connect { my (%opts) = @_; my $host = $opts{host} // "localhost"; my $port = $opts{port} // 5432; return "$host:$port"; } connect(host => "db.example.com", port => 3306);
서브루틴 레퍼런스
my $double = sub { return $_[0] * 2; }; print $double->(5); # 10 my @sorted = sort { $a <=> $b } @nums;
프로토타입 및 시그니처
use feature 'signatures'; sub add($a, $b) { return $a + $b; } sub greet($name, $greeting = "Hello") { return "$greeting, $name!"; }
정규식
매칭
if ($str =~ /pattern/) { print "matched\n"; } if ($str =~ /(\d+)/) { print "number: $1\n"; } my @matches = ($str =~ /(\w+)/g); # all matches
치환
$str =~ s/old/new/; # first occurrence $str =~ s/old/new/g; # global (all occurrences) $str =~ s/^\s+|\s+$//g; # trim whitespace (my $clean = $str) =~ s/\W//g; # non-destructive copy
수정자
/i대소문자 무시
/g전역 (모든 매치)
/m여러 줄 (^$가 줄 경계 매칭)
/s단일 줄 (.이 개행 문자 매칭)
/x확장 (공백 및 주석 허용)
일반 패턴
\d, \D숫자 / 비숫자
\w, \W단어 문자 / 비단어 문자
\s, \S공백 / 비공백
\b단어 경계
(?: ... )캡처 없는 그룹
(?<name> ... )이름 있는 캡처 ($+{name}으로 접근)
파일 I/O
열기 및 읽기
open(my $fh, '<', 'data.txt') or die "Cannot open: $!"; while (my $line = <$fh>) { chomp $line; print "$line\n"; } close($fh);
쓰기 및 추가
open(my $fh, '>', 'out.txt') or die "Cannot open: $!"; print $fh "Hello\n"; close($fh); open(my $fh, '>>', 'log.txt') or die "Cannot open: $!"; print $fh "entry\n"; close($fh);
전체 파일 읽기
use File::Slurp; my $content = read_file('data.txt'); my @lines = read_file('data.txt', chomp => 1);
파일 테스트
-e $path파일 존재 여부
-f $path일반 파일 여부
-d $path디렉터리 여부
-r / -w / -x읽기 / 쓰기 / 실행 가능
-s $path파일 크기 (바이트, 비어있으면 0)
-z $path파일 크기가 0
배열 및 해시
배열
my @arr = (1, 2, 3, 4, 5); push @arr, 6; # append my $last = pop @arr; # remove last my $first = shift @arr; # remove first unshift @arr, 0; # prepend my @slice = @arr[1..3]; # slice
배열 함수
scalar @arr원소 수
push / pop끝에 추가/제거
shift / unshift시작에서 제거/추가
splice(@a, 2, 1)인덱스 2에서 원소 1개 제거
sort @arr알파벳순 정렬
reverse @arr순서 뒤집기
grep { /pat/ } @arr패턴으로 필터링
map { $_ * 2 } @arr각 원소 변환
join(',', @arr)문자열로 합치기
해시
my %user = (name => "Alice", age => 30); $user{email} = "a\@b.com"; # add pair delete $user{age}; # remove pair my @keys = keys %user; my @vals = values %user;
해시 반복
while (my ($k, $v) = each %hash) { print "$k => $v\n"; } for my $key (sort keys %hash) { print "$key: $hash{$key}\n"; }
레퍼런스
레퍼런스 생성
my $scalar_ref = \$name; my $array_ref = \@arr; my $hash_ref = \%hash; my $anon_arr = [1, 2, 3]; # anonymous array ref my $anon_hash = {a => 1, b => 2}; # anonymous hash ref
역참조
print $$scalar_ref; # dereference scalar print $array_ref->[0]; # arrow notation print $hash_ref->{key}; # arrow notation my @copy = @$array_ref; # dereference to array my %copy = %$hash_ref; # dereference to hash
복잡한 자료구조
my @users = ( { name => "Alice", age => 30 }, { name => "Bob", age => 25 }, ); print $users[0]->{name}; # "Alice"
ref() 함수
ref($r) eq 'SCALAR'스칼라 레퍼런스
ref($r) eq 'ARRAY'배열 레퍼런스
ref($r) eq 'HASH'해시 레퍼런스
ref($r) eq 'CODE'서브루틴 레퍼런스
모듈
모듈 사용
use strict; use warnings; use List::Util qw(sum max min); use File::Basename; use Cwd qw(abs_path);
모듈 생성
# MyModule.pm package MyModule; use Exporter 'import'; our @EXPORT_OK = qw(helper); sub helper { return "help"; } 1; # module must return true
주요 코어 모듈
List::Utilsum, max, min, reduce, any, all
File::Basenamebasename, dirname, fileparse
File::Pathmake_path, remove_tree
Getopt::Long명령행 옵션 파싱
JSONencode_json, decode_json
LWP::Simpleget($url) — 간단한 HTTP 클라이언트
Data::Dumper자료구조 디버그 덤프
Carpcroak, confess — 더 나은 오류 메시지
CPAN
cpan install Module::Name # install from CPAN cpanm Module::Name # cpanminus (faster) perldoc Module::Name # read module docs