What's the simplest way to return the first line of a multi-line string in Perl?

[亡魂溺海] 提交于 2019-12-05 01:42:36

How about

( split /\n/, $s )[0]

?

You don't have to worry about \n being not cross-platform because Perl is clever enough to take care of that.

This isn't as simple as you like, but being simple just to be short shouldn't always be the goal.

You can open a filehandle on a string (as a scalar reference) and treat it as a file to read the first line:

my $string = "Fred\nWilma\Betty\n";
open my($fh), "<", \$string or die ...; # reading from the data in $string
my $first_line = <$fh>; # gives "Fred"
close $fh;

If you really wanted to, I guess you could reduce this to an expression:

$hash{$key} = do { open my($fh), "<", \$string; scalar <$fh> };

No matter which method you choose, you can always make a subroutine to return the first line and then use the subroutine call in your hash assignment.

sub gimme_first_line { ... }

$hash{$key } = gimme_first_line( \$string );
($str =~ /\A(.*?)$/ms)[0];

For large strings, this will be faster than

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

as suggested by Manni. [Edit: removed erroneous mention of split /\n/, $str, 1.]

If you want to include the terminal \n if it is present, add \n? just before the closing paren in the regex.

Kev
substr($s, 0, index($s, $/) > -1 ? index($s, $/) || () )
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!