views:

112

answers:

6

I want to split the a string if it contains ; or ,.

For example:

$str = "[email protected];[email protected],[email protected];[email protected];";

The expected result is:

result[0]="[email protected]";
result[1]="[email protected]";
result[2]="[email protected]";
result[3]="[email protected]";
+5  A: 
my $str = '[email protected];[email protected],[email protected];[email protected];';
my @result = split /[,;]/, $str;

Note that you can't use double-quotes to assign $str because @ is special. That's why I replaced the string delimiters with a single-quote. You could also escape them like so:

my $str = "a\@a.com;b\@b.com,c\@c.com;d\@d.com;";
Marcelo Cantos
Probably should do something like `grep { $_ } split(/[,;]/, $str)` to prevent a blank entry at the end of the list.
mscha
@mscha: There's no need. By default, the `split` function deletes empty trailing fields.
Marcelo Cantos
@Marcelo: Learned something new today. :-) Thanks.
mscha
+1 for pointing out that `@` interpolates in a double-quoted string. The OP must not have enabled warnings.
Sinan Ünür
A: 

split(/[.;]/, $str)

Paul
A: 

You could also use Text::Csv and use either ";" or "," for splitting. It helps to look at other things like printable characters etc as well.

weismat
A: 

Read this: http://www.comp.leeds.ac.uk/Perl/split.html

To split by ";" or ","

$test = "abc;def,hij";
@result = split(/[;,]/, $test);

Where the regex means to match on an escaped ; or , character. The end result will be that @result = ['abc','def','hij']

Danny Staple
+8  A: 

Sure, you can use split as shown by others. However, if $str contains full blown email addresses, you will be in a world of hurt.

Instead, use Email::Address:

#!/usr/bin/perl

use strict; use warnings;
use Email::Address;
use YAML;

print Dump [ map [$_->name, $_->address ],
    Email::Address->parse(
        q{[email protected];"Tester, Test" <[email protected]>,[email protected];[email protected]}
    )
];

Output:

---
-
  - a
  - [email protected]
-
  - 'Tester, Test'
  - [email protected]
-
  - c
  - [email protected]
-
  - d
  - [email protected]
Sinan Ünür
Good point, +1. Works even better if your example includes something like `"Tester, Test" <[email protected]>` (which many mailers produce).
mscha
A: 

To answer the question in the title of the mail (a little different from its text):

my $str = 'abc@xyz;qwe@rty;';

my @addrs = ($str =~ m/(\w+\@[\w\.]+)/g);

print join("<->", @addrs);
mmccoo