LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   perl:foreach (https://www.linuxquestions.org/questions/programming-9/perl-foreach-4606/)

katana 07-22-2001 10:08 PM

perl:foreach
 
hi!
I'm a perl new newbie :) recently i tried to do some programming....i got this xxx file, which has:

suzana, roslan

i want to append '@kym.edu.my' to each of the name, so the file would look like this:

suzana@kym.edu.my
roslan@kym.edu.my

so i did this in vi:

#!/usr/local/bin/perl
$file='/directory/of/file/xxx';
open(INFO,$file);
$lines=<INFO>;
close(INFO);
$add="\@kym.edu.my";
@line=split(/,/,$lines);
foreach $name(@line){
print "$name$add\n";
}

but instead i got this result:

suzana@kym.edu.my
roslan
@kym.edu.my

why is this? i've read some documentations but i still cant work out why it turned out the way it did...some help would be nice!

THANKS!!

jharris 07-23-2001 05:55 AM

Uhm... I wouldn't say that anything is wrong! Its just the last entry in the file (that appears to be comma delimited, going by your split statment) will have a \n on the end. If you input file takes the form of
Code:

name1,name2\n
then your code will produce
Code:

name1@domain.com\nname2\n@domain.com\n
which is gonna look like
Code:

name1@domain.com
name2
@domain.com

Try chomping the line so your code will look something like
Code:

#!/usr/local/bin/perl -w
$file = '/directory/of/file/xxx';

open(INFO,$file);
$lines = (<INFO>);
close(INFO);

$add = "\@kym.edu.my";
@line = split(/,/,$lines);
foreach $name (@line) {
    chomp($name);
    print "$name$add\n";
}

You always want to run Perl with -w that way it will give you lots of useful messages about potential problems.

HTH

Jamie...

katana 07-23-2001 09:45 PM

thanks a lot jamie!!! :D
well, it works!...when i ran the program, i got the output:

suzana@kym.edu.my
[space]roslan@kym.edu.my

that's good enough, but right now i'm trying to make the output look like this:

suzana@kym.edu.my
roslan@kym.edu.my

i supposed this is because in the xx file, it has:

suzana, roslan

how can i remove both the , and the space with split?

thanks a lot...i really appreciate you help!!:)

sykkn 07-24-2001 01:05 AM

You can replace the whitespace characters (\s)
with nothing using this line of code:
Code:

$name =~ s/\s+//g;
The whole file would look like this:
Code:

#!/usr/local/bin/perl -w
$file = '\\file.txt';

open(INFO,$file);
$lines = (<INFO> );
close(INFO);

$add = "\@kym.edu.my";
@line = split(/,/,$lines);
foreach $name (@line) {
    chomp($name);
    $name =~ s/\s+//g;
    print "$name$add\n";
}



All times are GMT -5. The time now is 09:02 AM.