Home: Perl Programming Help: Beginner:
output arrays to a file?



perlchaser
Novice

Aug 31, 2012, 12:26 PM


Views: 2116
output arrays to a file?

I have two arrays, @one, @two.
my @one = ('lisa','sarah','erica','jackie','maggie','mary')
my @two = ('teacher','student','doctor','lawyer','professor','reporter')

how can I output these two arrays into one file which looks like this:
-------------------
lisa teacher
sarah student
erica doctor
jackie lawyer
maggie professor
mary reporter
---------------------

Thank you,

Jackie


Laurent_R
Veteran / Moderator

Aug 31, 2012, 1:52 PM


Views: 2109
Re: [perlchaser] output arrays to a file?

Hi,

something like this:


Code
foreach my $i (0..5) { 
my $name = $one[$i];
my $job = $two[$i];
print "$name $job\n";
}



itsbaskar
Novice

Sep 1, 2012, 12:48 AM


Views: 2090
Re: [perlchaser] output arrays to a file?


Code
se warnings; 
use strict;

my @one = ('lisa','sarah','erica','jackie','maggie','mary');
my @two = ('teacher','student','doctor','lawyer','professor','reporter');
my $file="C:\\Temp\\testfile.txt";
my $totalItems=$#one;

open(FILEHANDLE, ">>", $file) or die "Cant Open file $file" ;

for my $i (0..$totalItems)
{
print (FILEHANDLE "$one[$i] $two[$i] \n");
}

close(FILEHANDLE);



itsbaskar
Novice

Sep 1, 2012, 12:53 AM


Views: 2089
Re: [perlchaser] output arrays to a file?

Using ">>" in open() will append contents of file opened .
Using ">" in open() Will rewrite the contents every time.


FishMonger
Veteran / Moderator

Sep 1, 2012, 9:16 AM


Views: 2074
Re: [perlchaser] output arrays to a file?

Here's another option:

Code
my @one = ('lisa','sarah','erica','jackie','maggie','mary'); 
my @two = ('teacher','student','doctor','lawyer','professor','reporter');

while ( (my $one = shift @one) and (my $two = shift @two) ) {
print "$one $two\n";
}