I have my perl code like this
my $test = "gsfdsd gsfgsfg sfghsdg
Starting
gahgahd vvsfdh";
$test=~ m/(.*)Starting(.*)/;
print"test value = $1 \n";
when I execute this code, I get nothing ie,
test value =
But when the $test
strings are in the same line ie,
my $test ="gsfdsd gsfgsfg sfghsdg Starting gahgahd vvsfdh";
I get the result for the print statement to be
test value = gsfdsd gsfgsfg sfghsdg.
What's the problem with the first case. The only difference is the inclusion of newline space. How to make the first code get executed.
The s
modifier to regexes causes .
to match newlines.
So your regex should be
$test=~ m/(.*)Starting(.*)/s;
to get the behaviour you want.
The dot doesn't match a newline unless you use the /s
modifier.
$test =~ /(.*)Starting(.*)/s;
Are you sure you want the newlines to be part of the captured strings?
Other answers have corrected your regex. But if your goal is to split a string into lines, use split
.
use strict;
use warnings;
use v5.10;
my $test = "gsfdsd gsfgsfg sfghsdg
Starting
gahgahd vvsfdh";
my @lines = split /\n/, $test;
say "First line: $lines[0]";
say "Second line: $lines[1]";
say "Third line: $lines[2]";
If your goal is to get the first and third lines, using split
means you don't need to know what the content of the second line is.
As others have said, .
matches any character except newline, so your .*
won't match beyond the end of the line
You can simply account for that whitespace using \\s*
. \\s
matches any whitespace character, and newline is a whitespace character
my $test = "gsfdsd gsfgsfg sfghsdg
Starting
gahgahd vvsfdh";
$test =~ m/(.*)\s*Starting/;
print "test value = $1 \n";
test value = gsfdsd gsfgsfg sfghsdg
It is very simple to achieve the solution using substitution and multi-line matching.
#!/usr/bin/perl
use strict;
use warnings;
my $test = "gsfdsd gsfgsfg sfghsdg
Starting
gahgahd vvsfdh";
$test=~ s/\n//mg;
print"test value = $test \n";
The output is as below,
test value = gsfdsd gsfgsfg sfghsdg Starting gahgahd vvsfdh
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.