Lesson 13 of 15
Regular Expressions
Regular Expressions
Perl is famous for its powerful regular expression support. We will use split with regex patterns and build pattern-matching subroutines.
Split with Regex
my @words = split(/\s+/, "hello world perl");
# ("hello", "world", "perl")
Building a Validator
You can write subroutines that check patterns manually:
sub is_digit_string {
my ($str) = @_;
my @chars = split("", $str);
foreach my $ch (@chars) {
if ($ch lt "0" or $ch gt "9") {
return 0;
}
}
return 1;
}
Grep and Map
grep filters a list, map transforms it:
my @nums = (1, 2, 3, 4, 5, 6);
my @evens = grep { $_ % 2 == 0 } @nums; # (2, 4, 6)
my @doubled = map { $_ * 2 } @nums; # (2, 4, 6, 8, 10, 12)
Your Task
Use grep to filter an array to only keep numbers greater than 3, then print each on its own line.
JS Transpiler loading...
Loading...
Click "Run" to execute your code.