Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How do I push a lines value into the first position of an array?

Status
Not open for further replies.

Geek8

Programmer
Apr 23, 2003
31
US
I am trying to open a file and then access each line and then enter that line into the "n"th position of an array. I am not sure how to do this. I am pretty new to perl, and would love some help. Here is my small code snippet. What could I do so I can take the undefined length of the value in each line and put it into the array. The byte size of the line in the INPUTFILE is going to constantly change, so I am not sure how to do this. I am perhaps not understanding the concept of @ARGV as I have used it incorrectly here. I know the array is going through to the correct number of lines, but the assignment of the value in that line is not occuring.

Code:

#!/bin/ksh/perl -w
use strict;

##Open file for reading counter##
my $vals = '/u01/home/test_csv.csv';
open (INPUTFILE, $vals)
or die "Could not open the $vals file $!\n";

my $i=0;
my @Total_file;

while (<INPUTFILE>){
$Total_file[$i]=@ARGV;
print &quot;$i value is : $Total_file[$i]\n&quot;;
$i++;
}

 
Just read the whole file into an array like this:
my $vals = '/u01/home/test_csv.csv';
open (INPUTFILE, $vals)
or die &quot;Could not open the $vals file $!\n&quot;;
@Total_file = <INPUTFILE>;
close(INPUTFILE);

 
Great! Thanks. It works like a charm.
 
Have a look at Tie::File [1], as that does alot of the work for you.

[1]
From the Synopsis:

use Tie::File;
tie @array, 'Tie::File', filename or die ...;

$array[13] = 'blah'; # line 13 of the file is now 'blah'
print $array[42]; # display line 42 of the file

$n_recs = @array; # how many records are in the file?
$#array -= 2; # chop two records off the end

for (@array) {
s/PERL/Perl/g; # Replace PERL with Perl everywhere in the file
}

Any changes to the file happen automatically, including handling of the record separator. See the perldoc (via the link above) for more info.





Barbie
Leader of Birmingham Perl Mongers
 
Mornin' all,

If the file is a CSV file then you will need to watch out for newlines embedded in the data. If the input record seperator is a newline and you aren't checking for newlines embedded in the data then you are going to get corrupted data.

So there.

Hello Barbie, I don't know you from London.pm.

Will.

will@hellacool.co.uk
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top