user2519656
user2519656

Reputation: 63

A Perl Program Which divides a String by spaces between them?

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

Answers (5)

Pradeep
Pradeep

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

Nikhil Jain
Nikhil Jain

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

TLP
TLP

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:

  • Normally, regex capture requires parentheses /(\S+)/, but when the /g modifier is used, and parentheses are omitted, the entire match is returned.
  • When using capture this way, you need to assure list context on the assignment. If the left hand parameter is a scalar, you would force list context with parentheses: my ($var) = ...

Upvotes: 7

user1811486
user1811486

Reputation: 1314

I think like simple....

$string = "hello how are you";  
print $_, "\n" for split ' ', $string;

Upvotes: 4

user2131116
user2131116

Reputation: 2861

@Array = split(" ",$string); then the @Array contain the answer

Upvotes: 2

Related Questions