CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

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

 



perlchaser
Novice

Aug 31, 2012, 12:26 PM

Post #1 of 5 (1474 views)
output arrays to a file? Can't Post

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

Post #2 of 5 (1467 views)
Re: [perlchaser] output arrays to a file? [In reply to] Can't Post

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

Post #3 of 5 (1448 views)
Re: [perlchaser] output arrays to a file? [In reply to] Can't Post


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

Post #4 of 5 (1447 views)
Re: [perlchaser] output arrays to a file? [In reply to] Can't Post

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

Post #5 of 5 (1432 views)
Re: [perlchaser] output arrays to a file? [In reply to] Can't Post

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";
}


 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives