Grace90
Grace90

Reputation: 227

How to concatenate certain strings to every element of array

I have a file WordNetTest3.txt which has some words separated by a white space and are elements of array called @unique_words . I want to concatenate TXD,RXD,CTS and RTS at the end of first element and these should become the four elements of a separate array . Then again I want to concatenate TXD,RXD,CTS and RTS at the end of second element and these should become the four elements of second array and so on with all elements of @unique_words .I'v written a code for one element but for all elements i am not able to iterate.

my $a='TXD';
my $b='RXD';
my $c='CTS';
my $d='RTS';


my $filenam = 'WordNetTest3.txt' ;
open my $f , '<' , $filenam or die "Cannot read '$filenam': $!\n" ;



for ( @unique_words ) {
$array0[0] =$unique_words[0].$a;
$array0[1] =$unique_words[0].$b;
$array0[2] =$unique_words[0].$c;
$array0[3] =$unique_words[0].$d;
}

open $f , '>' , $filenam or die "Cannot read '$filenam': $!\n" ;

foreach (@array0) {
print $f "$_\n";
}

#print $f "@array0\n" ;
close $f ;

Upvotes: 0

Views: 455

Answers (1)

Sobrique
Sobrique

Reputation: 53478

Once you open your file, you need to read from it. Perl doesn't know that you expect the filename to 'make it's way' into @unique_words.

You can read your file line by line by using:

while ( my $line = <$f> ) {

}

Likewise - even if you had declared @array0 properly, you'll be overwriting it each time, which won't do you much good.

Also: Turn on use strict; and use warnings;. They're practically mandatory when posting code to Stack Overflow.

Something like this might do the trick:

use strict;
use warnings;

my @suffixes = qw ( TXD RXD CTS RTS );

my $filenam = 'WordNetTest3.txt';
open my $input,  '<', $filenam       or die "Cannot read '$filenam': $!\n";
open my $output, '>', "$filenam.NEW" or die $!;

while ( my $line = <$input> ) {
    chomp($line);
    for my $suffix (@suffixes) {
        print {$output} $line . $suffix, "\n";
    }
}

close($input);
close($output);

(This is assuming it's one word per line in our file)

Upvotes: 2

Related Questions