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 wOOdy-Soft on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

printing column from an array

Status
Not open for further replies.

macubergeek

IS-IT--Management
Dec 29, 2004
41
US
I've read a file into an array this way:

open(DAT, "combined.nbe") || die("Could not open file!");
my @nessusdata=<DAT>;
close DAT;

The array consists of a thousand lines with 7 fields each line, deliminated with the pipe "|" symbol.

How do I print column 2 and 5 from this array?
 
print "$nessusdata[1] $nessusdata[4]\n" for @nessusdata;
 
Actually, try this:

Code:
foreach my $line (@nessusdata)
{
    my @line_info = split /|/, $line;
    print "$line_info[1] $line_info[4]\n";
}
Or, as you're reading in thousands of lines, to avoid reading all of that data into memory:
Code:
open(DAT, "combined.nbe") || die("Could not open file!");
while (my $line = <DAT>)
{
    my @line_info = split /|/, $line;
    print "$line_info[1] $line_info[4]\n";
}
close DAT;

- Rieekan
 
oops... yes, first you must split the file, my bad, thanks Rieekan :)

PS: he said "a thousand lines", not thousands of lines. ;-)
 
Two issues with the "split" function.
1) It is usually wise to escape a pipe character in a regex because it's used for alternation so you would be better to use "/\|/" rather than "/|/".
2) If it is possible that you could have empty fields in your data, you should use "split /\|/, $line, -1", otherwise, any trailing blank fields will be lost.

Trojan.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top