문제

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

도움이 되었습니까?

해결책

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.

다른 팁

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;
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top