perl : split a string using a newline character
Solution 1
You want to use the split
function, splitting the $string
on regions of space (" "
is special cased). Then take the generated list and join
it with the newline character "\n"
.
my $string = 'One Two Three';
my $output = join "\n", split " ", $string;
(view execution at http://ideone.com/Sd0Wp)
In your code you split the string on newlines. Naturally, this returns only one value because there are no newline characters.
Solution 2
You don't need use split-join for this task.
Just use regex to replace all spaces to newlines.
$string = 'One Two Three';
$string =~ s/\s/\n/g;
print $string;
Solution 3
Try this:
$string = 'One Two Three';
my @array3 = split (' ', $string);
print join ("\n", @array3);
This will split the strings on spaces and join them with newlines when you print them.
Solution 4
Your string doesnt contain newline characters. Possibly you need split it with space characters. So try this code:
$string = 'One Two Three';
my @array3 = split(/\s+/,$string);
iSim
Updated on June 25, 2020Comments
-
iSim almost 4 years
I want to split the words of a string with a newline character.
I have tried :
$string = 'One Two Three'; my @array3 = split("\n",$string);
I want the output like :
One Two Three
Can this be possible without using for loop?