On May 7, 2012, at 5:51 AM, lina wrote:

> On Mon, May 7, 2012 at 7:52 PM, Shawn H Corey <shawnhco...@gmail.com> wrote:
>> On 12-05-07 03:36 AM, lina wrote:
>>> 
>>> How can I insert the first file into the middle of the second file,
>> 
>> 
>> What code have you tried so far and please provide the expected output for
>> your example.
>> 
> 
> I can only write some preamble, here it what I came so far,
> 
> #!/usr/bin/env perl
> 
> use strict;
> use warnings;
> use autodie qw(open close);
> use 5.012;
> 
> open my $fh1, '<', "file1";
> open my $fh2, '<', "file2";
> 
> my @parts1;
> 
> my @parts2;
> 
> 
> while(<$fh2>){
>       @parts2 =  split /\s+/, $_;
> }

This loop continually reassigns the contents of the line read to @parts2. As a 
result, only the data from the last line will be saved.

If you only have one value per line, there is no need to split the line on 
whitespace. Just use chomp to remove the new line from the end, and use push to 
save all of the lines:

while(<$fh2>) {
  chomp;
  push(@parts2,$_);
}

That can be replaced with this:

@parts2 = <$fh2>;
chomp(@parts2);

> 
> while(<$fh1>){
>       #print $_;
>       @parts1 = split //,$_;
> }

That last line will split the input line into single characters, since the 
empty regular expression will match everywhere. Is that what you want to do?

Also, you are overwriting the entire array each time. Either fix this as for 
@parts2, or print out the array within the loop. Assuming that you want to 
split one whitespace, here is one way to do the latter (untested):

my $i = 0;
while(<$fh1>) {
  chomp;
  my( $first, @rest ) = split;
  print "$first $parts2[$i++] @rest\n";
}

> 
> 
> $ more file1
> 3
> 2
> 1
> 
> $ more file2
> 1  2
> 3  4
> 5  6
> 
> ******OUTPUT***********
> 
> 1     3       2
> 3     2       4
> 5     1       6


--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to