Question

i want to make this 2-Commands shorter, 1 line if it possible.

my $id = shift;
my @splittedID = split(" ", $id);
return $splittedID[0];

but it should have at the end the same functional. Thanks

Était-ce utile?

La solution

return (split " ", shift)[0];

Or, if you want:

(split " ", shift)[0];

(The result of the last line of a sub implicitly becomes the return value).

Even shorter (Perl 5.16 required for /r option):

$_[0]=~s/ .*//r

Of course, in actual production code, your original example is better, since it's readable.

Autres conseils

Because you just want the first item of the split and ' ' is a special pattern that skips all leading spaces, a regex can also solve this like so:

sub firstword {
    return (shift =~ /(\S+)/)[0];
}

my $x = firstword('asdf qwer jkl') # Equals 'asdf';
my $y = firstword('     qwer jkl') # Equals 'qwer';
my $z = firstword('             ') # Equals undef;

Also, the return keyword is optional of course, but shorter is not always better.

This is much more compact using a regular expression:

sub first_field {
  return unless $_[0] =~ /(\S+)/;
  $1;
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top