0

I have a question about Perl more out of curiosity than necessity. I have seen there are many ways to do a lot of things in Perl, a lot of the time the syntax seems unintuitive to me (I've seen a few one liners doing som impressive stuff).

So.. I know the function split returns an array. My question is, how do I go about printing the first element of this array without saving it into a special variable? Something like $(split(" ",$_))[0] ... but one that works.

3
  • 2
    substr() doesn't return an array, it returns a string. Commented May 23, 2013 at 23:44
  • 1
    Perhaps you meant to say that split returns an array? Commented May 23, 2013 at 23:46
  • Yes I meant split, my bad Commented May 23, 2013 at 23:54

3 Answers 3

4

You're 99% there

$ perl -de0

Loading DB routines from perl5db.pl version 1.33
Editor support available.

Enter h or `h h' for help, or `man perldebug' for more help.

main::(-e:1):   0
  DB<1> $a = "This is a test"

  DB<2> $b = (split(" ",$a))[0]

  DB<3> p $b
This
  DB<4> p "'$b'"
'This'
Sign up to request clarification or add additional context in comments.

1 Comment

He said he wanted to print it without assigning to a variable.
2

This should do it:

print ((split(" ", $_))[0]);

You need one set of parentheses to allow you to apply array indexing to the result of a function. The outer parentheses are needed to get around special parsing of print arguments.

Comments

0

Try this out to print the first element of a whitespace separated list. The \s+ regex matches one or more whitespace characters to split on.

 echo "1 2 3 4" | perl -pe 'print +(split(/\s+/, $_))[0]'

Also, see this related post.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.