0

Here's I want to archive. I want to split a one-liner comma-separated and insert @domain.com then join it back as comma-separated.

The one-liner contains something like:

username1,username2,username3

and I want to be something like:

[email protected],[email protected],[email protected]

So my Perl script that I tried which doesn't not work properly:

my $var ='username1,username2,username3';
my @tkens = split /,/, $var;
my @user;
       foreach my $tken (@tkens) {
           push (@user, "$tken\@domain.com");
       }
my $to = join(',',@user);

Is there any shortcut on this in Perl and please post sample please. Thanks

3
  • What is your current error output, if any? Commented Sep 9, 2015 at 2:09
  • There's no error but trying to print what is inside the $to shows a next line on @domain.com for username3. I am not sure what's causing it.
    – webdev.gk
    Commented Sep 9, 2015 at 2:12
  • I found out what is causing this. I have to trim trailing white spaces both left and right to make it properly..
    – webdev.gk
    Commented Sep 9, 2015 at 2:52

3 Answers 3

2

Split, transform, stitch:

my $var ='username1,username2,username3';
print join ",", map { "$_\@domain.com" } split(",", $var);
# ==> [email protected],[email protected],[email protected]
2
  • One thing I have learned is that I need to add this to trim trailing white spaces both left and right $var =~ s/^\s+|\s+$//g;
    – webdev.gk
    Commented Sep 9, 2015 at 2:51
  • if you are finding whitespace, then you have not been posting your actual script. Perhaps you are accepting from input or line-by-line from a file or STDIN? In that case, use chomp() on your input string.
    – Paul Allen
    Commented Sep 9, 2015 at 5:57
1

You could also use a regular expression substitution:

#!/usr/bin/perl
use strict;
use warnings;

my $var = "username1,username2,username3";
# Replace every comma (and the end of the string) with a comma and @domain.com
$var =~ s/$|,/\@domain.com,/g;
# Remove extra comma after last item
chop $var;
print "$var\n";
0
1

You already have good answers. Here I am just telling why your script is not working. I didn't see any print or say line in your code, so not sure how you are trying to print something. No need of last line in your program. You can simply suffix @domain.com with each value, push to an array and print it with join.

#!/usr/bin/perl
use strict;
use warnings;

my $var = 'username1,username2,username3';
my @tkens = split ',', $var;
my @user;
foreach my $tken (@tkens)
{
    push @user, $tken."\@domain.com"; # `.` after `$tken` for concatenation  
}
print join(',', @user), "\n"

Output:

[email protected],[email protected],[email protected]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.