2

Given the string Wibble eq wobble myhost.example.com I would like to be able to extract the last element.

My current effort is:

my @parts = split( /\s+/, "Wibble eq wobble myhost.example.com");
my $host = $parts[-1];
print "$host\n";

How do I do this with out the intermediate @parts array?

3
  • for that particular case, you can just use a regular expression to extract the last field: my ($host) = ($str =~ /(\S+)$/) Commented Jun 15, 2012 at 8:40
  • @salva - super, put that as an answer and you get a upvote :) Commented Jun 15, 2012 at 8:42
  • possible duplicate of Can this be done in one line? Commented Jun 15, 2012 at 15:17

2 Answers 2

6

Try this:

my $host = (split( /\s+/, "Wibble eq wobble myhost.example.com"))[-1];
Sign up to request clarification or add additional context in comments.

Comments

1

Alternatively (to the answer already given), try that:

my $host = pop [split /\s+/, "Wibble eq wobble myhost.example.com"];

or, if you dont like split:

my $host = pop [qw "Wibble eq wobble myhost.example.com"];

or, more perlish:

my $host = (qw "Wibble eq wobble myhost.example.com")[-1];

rbo

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.