0

When I try with a regular character instead of a newline such as X, the following works:

my $str = 'fooXbarXbaz';
$str =~ s/X.*//;
print $str;

foo

However, when the character to look for is \n, the code above fails:

my $str = "foo\nbar\nbaz";
$str =~ s/\n.*//;
print $str;

foo baz

Why is this happening? It looks like . only matches b, a, and r, but not the second \n and the rest of the string.

bp99
  • 242
  • 2
  • 13

1 Answers1

2

The . metacharacter does not match a newline unless you add the /s switch. This way it matches everything after the newline even if there is another newline.

$str =~ s/\n.*//s;

Another way to do this is to match a character class that matches everything, such as digits and non-digits:

$str =~ s/\n[\d\D]*//;

Or, the character class of the newline and not a newline:

$str =~ s/\n[\n\N]*//;

I'd be tempted to do this with simpler string operations. Split into lines but only save the first one:

$str = ( split /\n/, $str, 2 )[0]

Or, a substring up to the first newline:

$str = substr $str, 0, index($str, "\n");

And, I'm not recommending this, but sometimes I'll open a file handle on a reference to a scalar so I can read its contents line by line:

open my $string_fh, '<', \ $str;
my $line = <$string_fh>;
close $string_fh;

say $line;
brian d foy
  • 121,466
  • 31
  • 192
  • 551