0

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 ;
1
  • 1
    It's not really clear what result you want. Please add an extract of input file and expected result. Commented Mar 12, 2015 at 10:00

1 Answer 1

2

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)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.