Regular Expressions
Is site ki har doosri language regular expressions ko ek library ki tarah treat karti hai: aap ek regex module import karte ho, ek pattern object construct karte ho, aur usi par ek method call karte ho. Perl pattern matching ko directly apne syntax mein build karta hai. =~ ek string ko ek match ya substitution se bind karta hai; m/pattern/ (slashes use karte waqt m optional hai) match karta hai; s/pattern/replacement/ substitute karta hai. Koi import nahi, koi object nahi, koi method call nahi — ye language ke grammar ka hi part hai.
use strict;
use warnings;
my $text = "The year 2024 was followed by 2025.";
if ($text =~ /(\d{4})/) {
print "First match: $1\n";
}
my @years = $text =~ /(\d{4})/g;
print "All years: @years\n";
First match: 2024 All years: 2024 2025
Pattern mein parentheses capture karte hain — ek successful match ke baad, $1 wo hold karta hai jo bhi first parenthesized group ne match kiya tha. /g flag (global) list context mein, jaise upar @years mein, string ka har match return karta hai, pehle wale par stop hone ke bajaye.
s/pattern/replacement/ us par in place substitute karta hai jo bhi =~ se bound hai; /g add karne se har occurrence substitute hoti hai sirf pehli wali ke bajaye. (my $copy = $sentence) =~ s/.../.../; original string ko disturb kiye bina ek modified copy paane ka idiomatic tarika hai.
use strict;
use warnings;
my $sentence = "cats and cats and cats";
(my $copy = $sentence) =~ s/cats/dogs/;
print "One replaced: $copy\n";
(my $all = $sentence) =~ s/cats/dogs/g;
print "All replaced: $all\n";
if ("hello" =~ /\d/) {
print "matched\n";
} else {
print "no digits found\n";
}
One replaced: dogs and cats and cats All replaced: dogs and dogs and dogs no digits found
Next: references — Perl apne teen flat core types se nested, non-flat data structures kaise banata hai.
Practice exercise
my $str = "Order #4521 shipped" diya gaya hai, number ko extract karne ke liye ek regex match use karo aur use print karo.