Reputation: 63
I want my program to divide the string by the spaces between them
$string = "hello how are you";
The output should look like that:
hello
how
are
you
Upvotes: 0
Views: 280
Reputation: 3153
Split with regexp to account for extra spaces if any:
my $string = "hello how are you";
my @words = split /\s+/, $string; ## account for extra spaces if any
print join "\n", @words
Upvotes: 0
Reputation: 8352
You need a split for dividing the string by spaces like
use strict;
my $string = "hello how are you";
my @substr = split(' ', $string); # split the string by space
{
local $, = "\n"; # setting the output field operator for printing the values in each line
print @substr;
}
Output:
hello
how
are
you
Upvotes: 0
Reputation: 67900
You can do this is a few different ways.
use strict;
use warnings;
my $string = "hello how are you";
my @first = $string =~ /\S+/g; # regex capture non-whitespace
my @second = split ' ', $string; # split on whitespace
my $third = $string;
$third =~ tr/ /\n/; # copy string, substitute space for newline
# $third =~ s/ /\n/g; # same thing, but with s///
The first two creates arrays with the individual words, the last creates a different single string. If all you want is something to print, the last will suffice. To print an array do something like:
print "$_\n" for @first;
Notes:
/(\S+)/
, but when the /g
modifier is used, and parentheses are omitted, the entire match is returned.my ($var) = ...
Upvotes: 7
Reputation: 1314
I think like simple....
$string = "hello how are you";
print $_, "\n" for split ' ', $string;
Upvotes: 4
Reputation: 2861
@Array = split(" ",$string);
then the @Array
contain the answer
Upvotes: 2