问题
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