Visit Our UNIX and Linux User Community


Push records to array during implicit loop and write to file


 
Thread Tools Search this Thread
Top Forums Shell Programming and Scripting Push records to array during implicit loop and write to file
# 1  
Old 01-12-2010
Perl: Push records to array during implicit loop and write to file

NEWBIE ALERT!

Hi,
I'm 1 month into learning Perl and done reading "Minimal Perl" by Tim Maher (which I enjoyed enoumously). I'm not a programmer by profession but want to use Perl to automate various tasks at my job. I have a problem (obviously) and are looking for your much appreciated help.


THE TASK:
  1. I need to test the records from a text file with fields delimited by semicolon (infile.txt).
  2. At the end of the test I need to generate a report containing the tested records (outfile.txt).
  3. I want to use the implicit file loop available by the -n invocation option to go about the task in an AWKish way (but using AWK is not an option).
  4. By way of the implicit loop the read lines from infile.txt should be pushed into an array.
  5. In the END block the contents of the array should be written to the outfile.
My test file (infile.txt) contains 3 records of 3 semicolon delimited fields each:
1;2;3
a;b;c
4;5;6

The script is invoked from the command line by:
c:\perl test.pl infile.txt

My environment is Strawberry Perl, v.5.10.1 on Windows XP (Hey, I'm using Linux on my home PC!).

My stripped down script (stripped of everything irrelevant to the problem) is called test.pl:

Code:
 
#! usr/bin/perl -wlnaF';'
use strict;
{
  my $outfile = "outfile.txt";  # the name of the file to be written to
  my @resultArray;              # array to be populated by iterating thru the infile
  #### Assign fields to variables
  my $var1 = $F[0];     
  my $var2 = $F[1];     
  my $var3 = $F[2];     
  push @resultArray, ( "$var1 $var2 $var3" ); # Push fields into an array 
  print "Processed infile line no.: $.";      # reveals that all 3 infile lines were processed
  END { 
    print "Result array contains: " . @resultArray . " element(s)."; # reveals only 1 element in array
    writeToFile( \@resultArray, $outfile );    # pass array by reference and filename by value
  }
}
sub writeToFile {
  # Takes a reference to an array and a filename as input
  # Writes the contents of the array to the file
  my $array_ref = $_[0];
  my $filename = $_[1];
  open OUTFILE, "> $filename"
    or die;
  foreach ( @{ $array_ref } ) {
    print OUTFILE;
  }
  close OUTFILE;
}

THE PROBLEM:
Allthough all 3 records from the infile gets processed (a print statement reveals this during processing) only the first record makes it to the array and from the array to the outfile (another print statement and the outfile reveals this).

What am I doing wrong? - pls help!

Best regards,
John

---------- Post updated at 02:06 PM ---------- Previous update was at 12:52 AM ----------

The problem is SOLVED! :-)

By declaring @resultArray private with 'my' it apparantly gets reset every time the script loops through the next line from the infile.

The solution (probably not a nice one) was to declare @resultArray a global variable with 'our' in stead of 'my'.

Last edited by jospan; 01-11-2010 at 09:31 PM.. Reason: Clarifying

Previous Thread | Next Thread

10 More Discussions You Might Find Interesting

1. Shell Programming and Scripting

awk loop using array:wish to store array values from loop for use outside loop

Here's my code: awk -F '' 'NR==FNR { if (/time/ && $5>10) A=$2" "$3":"$4":"($5-01) else if (/time/ && $5<01) A=$2" "$3":"$4-01":"(59-$5) else if (/time/ && $5<=10) A=$2" "$3":"$4":0"($5-01) else if (/close/) { B=0 n1=n2; ... (2 Replies)
Discussion started by: klane
2 Replies

2. Programming

Javascript issue: array.push

I have a code snippet here that is supposed to vary values of certain parameter values: <script type="text/javascript"> // dynamic array of which its ultimate size is unknown // an array of arrays, each consisting of one variation var variations = ; // parameters of how to create a... (0 Replies)
Discussion started by: figaro
0 Replies

3. Shell Programming and Scripting

Write array contents to file

Hi, I have a bash script that currently holds some data. I am trying to write all the contents to a file called temp.txt. I am using echo ${array} > temp.txt The problem that I am experiencing is that the elements are being written horizontally in the file. I want them written... (5 Replies)
Discussion started by: Filter500
5 Replies

4. Shell Programming and Scripting

PERL : Read an array and write to another array with intial string pattern checks

I have an array and two variables as below, I need to check if $datevar is present in $filename. If so, i need to replace $filename with the values in the array. I need the output inside an ARRAY How can this be done. Any help will be appreciated. Thanks in advance. (2 Replies)
Discussion started by: irudayaraj
2 Replies

5. Shell Programming and Scripting

File 1 Column 1 value search in File 2 records, then loop?

Summary: I planned on using Awk to grab a value from File 1 and search all records/fields in file 2. If there is a match in File 2, print the first column value of the record of the match of File2. Continue this search until the end of file 2. Once at the end of file 2, grab the next value in... (4 Replies)
Discussion started by: Incog
4 Replies

6. Shell Programming and Scripting

parallel while loop based on the file records

Hi, I need to execute parallel with while loop. Input File(source_file.csv) contains filenames the below source_file.csv file contains Customer1.txt Product1.txt Sales.txt Emp.txt Dept.txt Based on the number of rows that file I want to run the script n' times. while... (2 Replies)
Discussion started by: onesuri
2 Replies

7. Shell Programming and Scripting

does bash have arrays that i can push into and run a for loop against?

Hi I have a bash script where i need to push some values into an array and when finished, run a for loop against that array for example myfile sausages|meat beef| meat carrot| veg ... ... for LINE in `cat myfile`; do FOOD=`echo $LINE | cut -d\| -f1` TYPE=`echo $LINE | cut... (4 Replies)
Discussion started by: rethink
4 Replies

8. Shell Programming and Scripting

PERL, push to hash of array problem

$key = "a"; $value = "hello"; %myhash = {} ; push @{ myHash{$key} }, $hello; print $myHash{$key}."\n"; this script prints "hello" but has following error message. Reference found where even-sized list expected at ./test line 5. can any one help me to fix this problem?? (3 Replies)
Discussion started by: bonosungho
3 Replies

9. Shell Programming and Scripting

Perl - if conditions is meet, push the last field of $_ into an array

I am using a seed file shown below to separate cisco devices by ios/os type. I want to bunch all the devices based on ios/os version. Once I find a match, I only want to push the ip address into the appropriate array. Example of seedfile 8 host1 (C3500XL-C3H2S-M) 11.0(5)WC17 10.1.44.21 9... (1 Reply)
Discussion started by: popeye
1 Replies

10. Programming

Can we use write() to modify/update intermediate records in a file

Hi, I have a database (a simple .dat file) which has multiple records (structure datatype) in it. I would like to know if we can use write() system call to update/modify intermediate records in this file (using C). If so, could somegive give a code snippet of the same. :-) Thanks in advance... (2 Replies)
Discussion started by: maverix
2 Replies

Featured Tech Videos