Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Extracting information from a string 2

Status
Not open for further replies.
Feb 16, 2003
87
GB
Hi everyone,

It's been a while since I posted here - let's see if the expert advice is still as good!

I have a variable (let's call it $variable) - that is in the format

"word1 word2 word3 anythingelse"

eg "simple domain aardvark anythingelse"

I need to be able to get word1, word2 and word3 into their own variables whilst ignoring anythingelse that may be after word3 - any ideas how I might do this?

If it helps, word1 will always be 'simple'. Unfortunately, I cannot change the structure of the original $variable.

Any help greatfully appreciated.

Simon
 
This should do the trick..


#!/usr/bin/perl

use strict;

my $variable = "simple domain aardvark anythingelse";

my %NEW;

my $i = 0;

my @words = split(/ /, $variable);
foreach my $word (@words) {
$NEW{$word} = $word;
last if $i > 3;
$i++;
}

print "$NEW{simple} - $NEW{domain} - $NEW{aardvark}\n\n";

M. Brooks
X Concepts LLC
 
Hi mbrooks,

Thanks for that but I can't seem to get it working.

The code works great but if I change any of the words in $variable - it doesn't seem to show up

Would it be to do with:

print "$NEW{simple} - $NEW{domain} - $NEW{aardvark}\n\n";

Shouldn't this be something like:

print "$NEW{word1} - $NEW{word2} - $NEW{word3}\n\n";

Any ideas?

Many thanks

Simon
 
Simon, your example shows $variable as containing 3 or more blank-delimited strings. Then you say "If it helps, word1 will always be 'simple'". This makes me wonder ...
Are the strings in $variable delimited by blanks? If so, this will work to get the first 3 into separate vars:

Code:
($word1, $word2, $word3)=split(/ /,$variable);

There's no loop required; split will just discard anything after the 3rd string.

But, if $variable is not actually laid out like this, it may not be so simple. What do you mean by
"If it helps, word1 will always be 'simple'."?
 
($word1,$word2,$word3,@crap)=split (/ /,$variable);

You'll need something to collect any garbage after word3, otherwise word 3 will contain any extra

HTH
--Paul
 
Apologies mikevh, normally I'd throw an array at the end of splits to catch any overspill.

Regards
--Paul
Regards
--Paul
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top