Capture string elements
my $string = "hello world";
if($string=~/^(\w+)\s+(\w+)$/) {
my firstWord = $1;
my secondWord = $1;
} |
my $string = "hello world";
if($string=~/^(\w+)\s+(\w+)$/) {
my firstWord = $1;
my secondWord = $1;
}
Or you can capture quickly if you are sure that the regular expression match :
$string=~/^(\w+)\s+(\w+)$/;
my firstWord = $1;
my secondWord = $1; |
$string=~/^(\w+)\s+(\w+)$/;
my firstWord = $1;
my secondWord = $1;
Case insensitive
To be case insensitiv, you have to add ‘i’ in your regular expression :
if($string=~/^K(.*)$/i) {
# word can start with 'K' or 'k'
my $result = $1;
} |
if($string=~/^K(.*)$/i) {
# word can start with 'K' or 'k'
my $result = $1;
}
Iterate
my $string = "hello world";
while($string=~/(\w)/g) {
my $result = $1;
} |
my $string = "hello world";
while($string=~/(\w)/g) {
my $result = $1;
}
Substitution
my $string = "hello world";
$string=~s/\s+/,/g;
print "$string\"n;
# $> hello,world |
my $string = "hello world";
$string=~s/\s+/,/g;
print "$string\"n;
# $> hello,world