Cơ Bản
Hello World
#!/usr/bin/perl use strict; use warnings; print "Hello, World!\n"; say "Hello, World!"; # with use feature 'say';
Chạy Perl
perl script.pl # run a file perl -e 'print "hi\n"' # run inline perl -ne 'print' file # process file line by line
Chú Thích & Tài Liệu
# single-line comment =pod Multi-line POD documentation =cut
Biến
Sigils
$scalarGiá trị đơn (chuỗi, số, tham chiếu)
@arrayDanh sách có thứ tự các scalars
%hashCặp key-value
$array[0]Truy cập phần tử mảng đơn (ngữ cảnh scalar)
$hash{key}Truy cập giá trị hash đơn (ngữ cảnh scalar)
Biến Scalar
my $name = "Perl"; # string my $version = 5.40; # number my $count = 42; # integer my $undef; # undefined (undef) my $combined = "$name v$version"; # interpolation
Ngữ Cảnh
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
Biến Đặc Biệt
$_Biến mặc định (topic)
@_Tham số của subroutine
$!Thông báo lỗi hệ thống
$@Lỗi từ eval
$0Tên chương trình
@ARGVTham số dòng lệnh
%ENVBiến môi trường
Toán Tử
Toán Tử So Sánh
==, !=, <, >, <=, >=So sánh số
eq, ne, lt, gt, le, geSo sánh chuỗi
<=>Spaceship số (trả về -1, 0, 1)
cmpSpaceship chuỗi
=~Khớp / ràng buộc regex
!~Không khớp regex
Toán Tử Chuỗi
my $full = "Hello" . " " . "World"; # concatenation my $line = "-" x 40; # repetition my $len = length($full); # 11
Toán Tử Logic
&& / andLogic AND (ưu tiên thấp: and)
|| / orLogic OR (ưu tiên thấp: or)
// Defined-or (trả về trái nếu đã định nghĩa)
! / notLogic NOT
? :Điều kiện ba ngôi
Luồng Điều Khiển
Điều Kiện
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
Vòng Lặp
for my $i (0..9) { print "$i\n"; } foreach my $item (@array) { print "$item\n"; } while ($line = ) { chomp $line; } until ($done) { last if check(); }
Điều Khiển Vòng Lặp
nextBỏ qua lần lặp tiếp theo (như continue)
lastThoát vòng lặp (như break)
redoKhởi động lại lần lặp hiện tại
next LABELBỏ qua lần lặp tiếp theo của vòng lặp có nhãn
last LABELThoát vòng lặp có nhãn
Given / When
use feature 'switch'; given ($status) { when ("ok") { say "success"; } when ("error") { say "failed"; } default { say "unknown"; } }
Subroutines
Subroutine Cơ Bản
sub greet { my ($name) = @_; return "Hello, $name!"; } my $msg = greet("Alice");
Tham Số Mặc Định & Có Tên
sub connect { my (%opts) = @_; my $host = $opts{host} // "localhost"; my $port = $opts{port} // 5432; return "$host:$port"; } connect(host => "db.example.com", port => 3306);
Tham Chiếu Subroutine
my $double = sub { return $_[0] * 2; }; print $double->(5); # 10 my @sorted = sort { $a <=> $b } @nums;
Prototypes & Signatures
use feature 'signatures'; sub add($a, $b) { return $a + $b; } sub greet($name, $greeting = "Hello") { return "$greeting, $name!"; }
Regex
Khớp
if ($str =~ /pattern/) { print "matched\n"; } if ($str =~ /(\d+)/) { print "number: $1\n"; } my @matches = ($str =~ /(\w+)/g); # all matches
Thay Thế
$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
Modifiers
/iKhông phân biệt hoa/thường
/gToàn cục (tất cả khớp)
/mNhiều dòng (^$ khớp ranh giới dòng)
/sMột dòng (. khớp ký tự xuống dòng)
/xMở rộng (cho phép khoảng trắng và chú thích)
Pattern Phổ Biến
\d, \DChữ số / không phải chữ số
\w, \WKý tự từ / không phải ký tự từ
\s, \SKhoảng trắng / không phải khoảng trắng
\bRanh giới từ
(?: ... )Nhóm không bắt
(?<name> ... )Bắt có tên (truy cập qua $+{name})
File I/O
Mở & Đọc
open(my $fh, '<', 'data.txt') or die "Cannot open: $!"; while (my $line = <$fh>) { chomp $line; print "$line\n"; } close($fh);
Ghi & Thêm Vào
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);
Đọc Toàn Bộ File
use File::Slurp; my $content = read_file('data.txt'); my @lines = read_file('data.txt', chomp => 1);
Kiểm Tra File
-e $pathFile tồn tại
-f $pathLà file thường
-d $pathLà thư mục
-r / -w / -xĐọc được / ghi được / thực thi được
-s $pathKích thước file tính bằng byte (0 nếu rỗng)
-z $pathFile có kích thước bằng 0
Arrays & Hashes
Mảng
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
Hàm Mảng
scalar @arrSố phần tử
push / popThêm/xóa từ cuối
shift / unshiftXóa/thêm từ đầu
splice(@a, 2, 1)Xóa 1 phần tử tại chỉ số 2
sort @arrSắp xếp theo thứ tự bảng chữ cái
reverse @arrĐảo ngược thứ tự
grep { /pat/ } @arrLọc theo pattern
map { $_ * 2 } @arrBiến đổi mỗi phần tử
join(',', @arr)Nối thành chuỗi
Hashes
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;
Lặp Qua Hash
while (my ($k, $v) = each %hash) { print "$k => $v\n"; } for my $key (sort keys %hash) { print "$key: $hash{$key}\n"; }
References
Tạo References
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
Dereference
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
Cấu Trúc Dữ Liệu Phức Tạp
my @users = ( { name => "Alice", age => 30 }, { name => "Bob", age => 25 }, ); print $users[0]->{name}; # "Alice"
Hàm ref()
ref($r) eq 'SCALAR'Tham chiếu đến scalar
ref($r) eq 'ARRAY'Tham chiếu đến array
ref($r) eq 'HASH'Tham chiếu đến hash
ref($r) eq 'CODE'Tham chiếu đến subroutine
Modules
Dùng Modules
use strict; use warnings; use List::Util qw(sum max min); use File::Basename; use Cwd qw(abs_path);
Tạo Module
# MyModule.pm package MyModule; use Exporter 'import'; our @EXPORT_OK = qw(helper); sub helper { return "help"; } 1; # module must return true
Core Modules Phổ Biến
List::Utilsum, max, min, reduce, any, all
File::Basenamebasename, dirname, fileparse
File::Pathmake_path, remove_tree
Getopt::LongPhân tích tham số dòng lệnh
JSONencode_json, decode_json
LWP::Simpleget($url) — HTTP client đơn giản
Data::DumperDebug dump cấu trúc dữ liệu
Carpcroak, confess — thông báo lỗi tốt hơn
CPAN
cpan install Module::Name # install from CPAN cpanm Module::Name # cpanminus (faster) perldoc Module::Name # read module docs