dakin999 wrote:
> 
> I have following code which works ok. It does following:
> 
> 1. reads data from a input file
> 2. puts the data into seperate variables in a array

This is where you are getting confused. The data should be /either/ in separate
variables /or/ in an array. See below.

> 3. reads from this array and prints out to another file
> 
> It works except that it prints the same record 4 times. I can see I
> have missed some thing in my array definition as their are 4 elements
> in array

No. There is only one element in your array - it is a reference to an anonymous
array.

> it is printing 4 times each element and then moving to next
> element till it reaches eof().
>
> while (<input>)  #reading a line from file
> # Read the line into a set of variables
>     ($1,$2,$3,$4)=split(/,/,$_);

You have a missing open brace here. This code won't compile.

Never use $1, $2 etc. for you own purposes. Anything that doesn't start with a
letter (and even then a couple of those that do) are used by Perl without your
permission and may well be modified without you noticing.

For now, Let's say you meant

  my ($aa, $bb, $cc, $dd) = split /,/;

> # Buid an array with these varaibles
>     my @array = ([$1, $2, $3, $4]);

You've initialised @array to a single item. That item is [$aa, $bb, $cc, $dd],
which is an anonymous array. It's equivalent to

  my @array;
  $array[0] = [$aa, $bb, $cc, $dd];

>     foreach my $r(@array) {

So this loop is executed one only, with $r equal to [$aa, $bb, $cc, $dd].

>     foreach (@$r){

Now @$r is the same as the list ($aa, $bb, $cc, $dd), so within this loop $_
will be set to each of those values in turn. But you never use $_ within it so
the values in @$r are irrelevant - all that matters is that there are four of
them so you will do this four times.

> 
> ...     print <out> "$1\n";
>         print <out> "$2\n";
>         print <out> "$3\n";
>         print <out> "$4\n";
>         print <out> "\n";

And what you try to do is just print each of the four original variables for
each element of @$r, but this is incorrect syntax and again won't compile. What
you mean is

  print out "xx\n";

If it was correct it would be the same as writing

  foreach ('a' .. 'd') {
    print out 1, "\n";
    print out 2, "\n";
    print out 3, "\n";
    print out 4, "\n";
  }

can you see that?



I suggest you meant to split into an array in the first place, and write
something like

  while (<input>)  { # read a line from file

    # split the line into an array
    my @data = split /,/;

    foreach my $r (@data) {
      print out "$r\n";
    }
  }



Please try to post real code that you are having problems with, or we could
spend a long time finding that all you have done is copied it wrongly into your
questions here.

Bed now <yawn>.

HTH,

Rob

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/


Reply via email to