Dhanashri P
Dhanashri P

Reputation: 111

To split a space or comma seperated string into a list in perl

Case : I have a string $str = "a, b , c" How can I split the string to get a list? The split expression that I could come up with is :

  1. split('[,\s]+', $str)
  2. split(/,/, $techoptionGiven);

The desired behavior @array = [abc]

Upvotes: 0

Views: 1105

Answers (1)

Dave Cross
Dave Cross

Reputation: 69314

Your first option seems to work:

#!/usr/bin/perl

use strict;
use warnings;
use feature 'say';

use Data::Dumper;

my $str = "a, b , c";

say Dumper split('[,\s]+', $str);

Output:

$VAR1 = 'a';
$VAR2 = 'b';
$VAR3 = 'c';

Personally, I'd want to emphasise the fact that the first argument to split() is a regex, not a string.

say Dumper split(/[,\s]+/, $str);

Upvotes: 1

Related Questions