snoofkin
snoofkin

Reputation: 8895

Perl anonymous list question

Why this doesnt work?

my $str = 'we,you,them,us';

print $(split($str,','))[0];

I know I can do:

my @str = split...

but I remember there is a way to skip that.

Thanks,

Upvotes: 0

Views: 332

Answers (3)

Eric Strom
Eric Strom

Reputation: 40142

Any time you need to only access a small portion of a function's return value, you should check to see if there is a smaller scoped function you can use. In this case, I might use a regular expression:

print $str =~ /^([^,]*)/;

Upvotes: 5

Gea-Suan Lin
Gea-Suan Lin

Reputation: 726

Using [split $str, ',']->[0]; would be fine.

Upvotes: -1

jira
jira

Reputation: 3944

You have the order of arguments for split reverse. There should be no dollar sign in front of the parens. The following works (the plus sign forces perl to evaluate the following as expression):

use strict;
use warnings;

my $str = 'we,you,them,us';

print +(split(',',$str))[0];

Upvotes: 8

Related Questions