Perl matches multiple lines on the same line (anything inside double and single quotes)

I thought it should be simple by matching strings in double / single quotes on one line

for example, the next line in one line

"hello" 'world' 'foo' "bar"

I have print /(".*?")|('.*?')/g;

but i got the following errors

Use of uninitialized value in print at ...

+4
source share
3 answers

The following are the warnings you mentioned:

use strict;
use warnings;

my $str = q{"hello" 'world' 'foo' "bar"};

print $str =~ /(".*?")|('.*?')/g;

This is because your regular expression will match only one or the other of the capture groups. The other will not match and he will return undef.

The following is shown:

while ($str =~ /(".*?")|('.*?')/g) {
    print "one = " . (defined $1 ? $1 : 'undef') . "\n";
    print "two = " . (defined $2 ? $2 : 'undef') . "\n";
    print "\n";
}

Outputs:

one = "hello"
two = undef

one = undef
two = 'world'

one = undef
two = 'foo'

one = "bar"
two = undef

To get the desired behavior, simply place the capture group around the entire expression.

print $str =~ /(".*?"|'.*?')/g;
+3
source

, Text:: ParseWords

use Text::ParseWords;

my $s = q{"hello" 'world' 'foo' "bar"};
my @words = quotewords('\s+', 0, $s);

use Data::Dumper; print Dumper \@words;

$VAR1 = [
      'hello',
      'world',
      'foo',
      'bar'
    ];
+3

anoher using backlink:

use strict;
use warnings;

my $str = q{"hello" 'world' 'foo' "bar"};

while ($str =~ /(["']).*?\1/g) {
    print  $&  . "\n";
}
-1
source

Source: https://habr.com/ru/post/1534969/


All Articles