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:
saving an array for other parts of script

 



regex2012
User

Feb 23, 2016, 7:48 AM

Post #1 of 2 (1064 views)
saving an array for other parts of script Can't Post

I'd like to know how to save an array so that I can use it in my program. What I mean is I have this:

Code
open my $FH1, '<', '/tmp/active_q1.txt' or die "unable to open file 'file' for reading : $!"; 
open my $fh6, '>>', '/tmp/final.txt' or die "unable to open file 'file' for reading : $!";
while (<$FH1>) {
my @fields = split(',', $_);
local $" = ',';
print $fh6 "@fields[1,2]\n";
}


I'd like to be able to print out @fields in other parts of the script, but since the portion that has @fields is in parenthesis, I can't do that. If I remove the final parenthesis and put them at the end of the script instead, that causes other issues. Is there a way to save @ fields so it can be used all through the script?

It looks like it can be done by subroutines. Not sure exactly how, I see some documentation where it is done by reference and some not.


(This post was edited by regex2012 on Feb 23, 2016, 8:06 AM)


BillKSmith
Veteran

Feb 23, 2016, 9:08 AM

Post #2 of 2 (1058 views)
Re: [regex2012] saving an array for other parts of script [In reply to] Can't Post

You need to save more than @fields. You need all of them.

Save all of them in an array-of-arrays which has package scope.


Code
use strict; 
use warnings;
open my $FH1, '<', '/tmp/active_q1.txt' or die "unable to open file 'file' for reading : $!";
my @active;
push @active, [split ',', $_] while (<$FH1>) ;
close $FH1;


foreach my $fields (@active) {
local $" = ',';
print "@{$fields}[1,2]\n";
}

Good Luck,
Bill

 
 


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

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