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

社会主义新天地 提交于 2019-12-06 20:27:56

问题


When I say simple, I mean, within an expression, so that I can stick it in as a value in a hash without preparing it first. I'll post my solution but I'm looking for a better one that reminds me less of VB. :)


回答1:


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.




回答2:


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 );



回答3:


($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.




回答4:


substr($s, 0, index($s, $/) > -1 ? index($s, $/) || () )


来源:https://stackoverflow.com/questions/428065/whats-the-simplest-way-to-return-the-first-line-of-a-multi-line-string-in-perl

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