Here's the example:
my $string = "Here is our test string."; my $word; ( $word, $string ) = split /^(\w+)\b/, $string, 2;
Now you have $word containing the first word found in $string, assuming a word, to you, contains nothing but word characters. And $string now contains only everything after the first word (including the leading space).
To put the word back, just concatenate:
$string = $word . $string;
This could also be done with a regular plain vanilla pattern match in several ways, but I'll do it the easy way:
my $string = "This is the test string."; my $word; ( $word, $string ) = $string =~ m/^(\w+)\b(.*)/;
As you can see above, we don't really care about greediness of .* because we want it to be greedy enough to grab everything following the first word. If you have newlines within the string you'll have to use the /s modifier.
Here's another approach with substitution:
my $string = "Here is our test string."; my $word = $string =~ s/^(\w+)\b(.*)/$2/;
Now you've pushed the first word into $word, and captured everything else in $2, which then becomes the substitute for the original string. Again, we don't mind of .* is greedy as long as it leaves enough for a word at the beginning of the string followed by a word boundry. Again, if there is a newline in the string, you'll need the /s modifier on the regexp.
With all of the examples above, you put humpty dumpty back together again by concatenating:
$string = $word . $string;
I hope this helps!
Dave
"If I had my life to do over again, I'd be a plumber." -- Albert Einstein
In reply to Re: take out section of a string then put it back
by davido
in thread take out section of a string then put it back
by mr_evans2u
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |