Perl regular expressions and text processing
Regular expressions are built into Perl. The match operator =~ /pattern/ tests a string, and parentheses capture groups. Named groups, written (?<name>...), are stored in the %+ hash, which makes patterns self-documenting. In list context with the /g flag a match returns every captured piece at once.
Perl
use strict;
use warnings;
my $line = "2024-03-15 ERROR disk full on /dev/sda1";
if ($line =~ /^(?<date>\d{4}-\d{2}-\d{2})\s+(?<level>[A-Z]+)\s+(?<message>.*)$/) {
print "$+{date} | $+{level} | $+{message}\n";
}
my $text = "cat bat rat hat";
my @letters = $text =~ /\b(\w)at\b/g;
print scalar(@letters), " matches: @letters\n";
(my $copy = $text) =~ s/(\w)at/\U$1\Eat/g;
print "$copy\n";
(my $dna = "AACGT") =~ tr/ACGT/TGCA/;
my $count = ($text =~ tr/a//);
print "$dna $count\n";
my $prices = "apple=3, pear=12, fig=7";
(my $doubled = $prices) =~ s/(\d+)/$1 * 2/ge;
print "$doubled\n";
print join("|", split /\s*,\s*/, "a , b,c ,d"), "\n";