Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a one-liner to get the first element of a split?

Tags:

perl

Instead of writing:

@holder = split /\./,"hello.world";  print @holder[0]; 

is it possible to just do a one-liner to just get the first element of the split? Something like:

print (split /\./,"hello.world")[0] 

I get the following error when I try the second example:

print (...) interpreted as function at test.pl line 3. syntax error at test.pl line 3, near ")[" 
like image 400
user794479 Avatar asked May 29 '12 12:05

user794479


People also ask

How do you get your first element after a split?

To split a string and get the first element of the array, call the split() method on the string, passing it the separator as a parameter, and access the array element at index 0 . For example, str. split(',')[0] splits the string on each comma and returns the first array element.

How do you separate the first element of a list in Python?

Use the str. split() method with maxsplit set to 1 to split a string and get the first element, e.g. my_str. split('_', 1)[0] . The split() method will only perform a single split when maxsplit is set to 1 .


2 Answers

You should have tried your hunch. That’s how to do it.

my $first = (split /\./, "hello.world")[0]; 

You could use a list-context assignment that grabs the first field only.

my($first) = split /\./, "hello.world"; 

To print it, use

print +(split /\./, "hello.world")[0], "\n"; 

or

print ((split(/\./, "hello.world"))[0], "\n"); 

The plus sign is there because of a syntactic ambiguity. It signals that everything following are arguments to print. The perlfunc documentation on print explains.

Be careful not to follow the print keyword with a left parenthesis unless you want the corresponding right parenthesis to terminate the arguments to the print; put parentheses around all arguments (or interpose a +, but that doesn't look as good).

In the case above, I find the case with + much easier to write and read. YMMV.

like image 143
Greg Bacon Avatar answered Sep 27 '22 18:09

Greg Bacon


If you insist on using split for this then you could potentially be splitting a long string into multiple fields, only to discard all but the first. The third parameter to split should be used to limit the number of fields into which to divide the string.

my $string = 'hello.world';  print((split(/\./, $string, 2))[0]); 

But I believe a regular expression better describes what you want to do, and avoids this problem completely.

Either

my $string = 'hello.world'; my ($first) = $string =~ /([^.]+)/; 

or

my $string = 'hello.world'; print $string =~ /([^.]+)/; 

will extract the first string of non-dot characters for you.

like image 32
Borodin Avatar answered Sep 27 '22 19:09

Borodin