Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

perl loop to add element from last line to new line.

Status
Not open for further replies.

Natalie30

Programmer
Feb 5, 2003
12
0
0
US
my $data_file = "/root/bin/load.data2";
open(FILE,&quot;<$data_file&quot;) or die &quot;Cant open $data_file2: $!\n&quot;;
my @log = <FILE>;
close(FILE);
my $last_element='&quot;0&quot;';
while (<>){
chomp;
@log = split ',';
print &quot;$_, $last_element\n&quot;;
$last_element = $log[$#log];
}

just need a little help with this, not sure if my code is going in the right direction.
thanks.
Nat
 
Ah, not quite. The [tt]while (<>)[/tt] is reading lines from standard input. You've already read lines from [tt]FILE[/tt].

You can change the script to:
[tt]my $data_file = &quot;/root/bin/load.data2&quot;;
open(FILE,&quot;<$data_file&quot;) or die &quot;Cant open $data_file2: $!\n&quot;;
my $last_element='&quot;0&quot;';
while (<FILE>){
chomp;
my @log = split ',';
print &quot;$_, $last_element\n&quot;;
$last_element = $log[$#log];
}
close(FILE);
[/tt]

There's no real need to read the entire file in first before processing it in this case. If you really wanted to do that, you could keep your code as is, but change
[tt]while (<>) {
chomp;
@log = split ',';
print &quot;$_, $last_element\n&quot;;
$last_element = $log[$#log];
}
[/tt]

to:
[tt]foreach (@log) {
chomp;
my @list = split ',';
print &quot;$_, $last_element\n&quot;;
$last_element = $list[$#list];
}
[/tt]

[tt]foreach[/tt] will do the block for each element in the array, setting [tt]$_[/tt] to the element each time.

Note that the block itself now uses [tt]@list[/tt] inteaed of [tt]@log[/tt] for the split elements. Using [tt]@log[/tt] as you were got rid of the text of the file you'd read into that same list.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top