Desmond Lim wrote:
>
> I have 3 arrays @arr1, @arr2 and @arr3.
>
> I need to print them into the same file and I'm doing this.
>
> open FILE, <file name>;
> print FILE "@arr1\n";
> print FILE "@arr2\n";
> print FILE "@arr3\n";
> close FILE;
>
> I would like to shorten it to
>
> for ($i=0;$i<4;$i++) {
>   print FILE "@arr$i\n";
> }
>
> I know there is an error but is there a work around to this?

There should be no 'errors' as such, because what you've written
is valid Perl, but there are several problems here.

- Your 'open' statement is is doing

   open FILE, glob ('file name');

which I don't think you meant.

- This form of the 'for' statement is taken from C, and is
rarely the best way to do things in Perl. Your loop also
starts at zero, when there isn't a @arr0 variable. Use

  for (1 .. 3) {
    :
  }

- The 'print' statement is expanding variables @arr and $i
separately in the string. @arr doesn't exist, so you'll just
get $i in the output records.


The answer to your question is that you need to use

    "@{qq(arr$i)}\n"

as your string but, if anybody catches you doing it, I didn't
tell you, OK?

It's important to

  use strict;   # always
  use warnings; # usually

and 'strict' will, quite rightly, prevent you from doing anything
like this. In this case it's only possible because you've used
meaningless names for your arrays. (It's hard to guess what, say,
@arr2 contains without asking you.)

Just what is wrong with

  print FILE "@arr1\n";
  print FILE "@arr2\n";
  print FILE "@arr3\n";

anyway? It's a great deal clearer than

  for (1 .. 3) {
    print FILE "@{qq(arr$i)}\n";
  }

and fractionally faster.

If you insist on doing it with 'strict' enabled then

  for ([EMAIL PROTECTED], [EMAIL PROTECTED], [EMAIL PROTECTED]) {
    print "@$_\n";
  }

is the way.

Cheers,

Rob



-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to