Process each input record as an array of elements

D

Dmitry

Hello everyone,

I have a really simple question here:

I have a plain space delimited file that I want to read with WHILE
loop 1 line at the time and process each input record as an array of
elements. Then, on the next iteration of the loop, clean up the array
and populate it with contents of the next input record. Each input
record consists of 7 fields / elements separated by spaces. The reason
I need this is because I have to switch FIRST and LAST elements of the
record by places. For example:

Before: aaa bbb ccc ddd eee fff ggg

After: ggg bbb ccc ddd eee fff aaa

I am having trouble assigning contents of each input record to an
array.

If I can do that, then I will be use POP and UNSHIFT Perl functions to
switch the elements.

Here is what I have so far:

my $pop_element = ‘';
my @print_array = ();

open (OLD, "< $fname_out") || die "Cannot open OLD file
$fname_out!";
open (NEW, "> $temp") || die "Cannot open NEW file $temp!";

while (<OLD>) {
@print_array = "$_\n";
$pop_element = pop ( @print_array );
unshift ( @print_array, $pop_element );
$_ = @print_array;
print NEW "$_\n" || die "Cannot write NEW file $temp!";
}
close (OLD) || die "Cannot close OLD file $fname_out!";
close (NEW) || die "Cannot close NEW file $temp!";
rename ( $temp, $fname_out ) || die "Cannot rename NEW file $temp
to $fname_out!";
}

Any suggestions would be greatly appreciated.

Thanks,

Dmitry.
 
R

Roy Johnson

This newsgroup is defunct. Use comp.lang.perl.misc instead.

This should do more or less what you want (season to taste):

while (<>) {
@elems = split; # split on whitespace
@elems[0,-1] = @elems[-1,0]; # swap first and last elements
print join(',', @elems), "\n";
}
 
D

Dmitry

Thanks Roy, it worked perfectly!

I did, however post the same question to per.msc group, just curious
about other possible alternatives.

Best regards,

Dmitry.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,996
Messages
2,570,238
Members
46,826
Latest member
robinsontor

Latest Threads

Top