Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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. :)

like image 657
Kev Avatar asked Jan 09 '09 13:01

Kev


3 Answers

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.

like image 136
innaM Avatar answered Oct 09 '22 09:10

innaM


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 );
like image 31
brian d foy Avatar answered Oct 09 '22 09:10

brian d foy


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

like image 20
j_random_hacker Avatar answered Oct 09 '22 11:10

j_random_hacker