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. :)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With