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: Re: [AndrewF] Need help printing out only certain items in a file: Edit Log



2teez
Novice

Jul 6, 2013, 1:51 PM


Views: 501
Re: [AndrewF] Need help printing out only certain items in a file

If I may first comment on your code:
There are a number of things that are good practice using Perl.
1. You should use 3 - argument of open function in Perl,
2. Use a lexical scope file handles,
3. Check the return of the both "open" and "close" function or you use "autodie".
All of that is demonstrated below:

Code
 open my $fh,' <', 'practice.txt' or die "can't open file: $!"; 
...
close $fh or die "can't close file: $!";


That been said, this is one way of going what you wanted:
After opening the file, you could step through the file a line at a time, split on "/" and get the value you wanted.
Make an ARRAY of ARRAY and store this values.
Then you can print out all the values you want.

Please let me give you a head up with a little code that does what I think you want.


Code
use warnings; 
use strict;
use Data::Dumper;

<DATA>; #remove the heading if not needed

my @data;
my $counter;

while(<DATA>){
chomp;
$counter = 0;
for ((split/\|/,$_)[1,2]){
push @{$data[$counter++]},$_;
}
}

print Dumper \@data;
#OR
print join $/=> map @$_ => @data;

__DATA__
Header1|Header2|Header3|Header4
Microsoft|MSFT|UN|85
Oracle|ORCL|UN|10.0
Johnson & Johnson|JNJ|US|5


This produces:

Code
$VAR1 = [ 
[
'MSFT',
'ORCL',
'JNJ'
],
[
'UN',
'UN',
'US'
]
];

MSFT
ORCL
JNJ
UN
UN
US


For ARRAY of ARRAY, please read up http://perldoc.perl.org/perldsc.html#ARRAYS-OF-ARRAYS


(This post was edited by 2teez on Jul 6, 2013, 2:07 PM)


Edit Log:
Post edited by 2teez (Novice) on Jul 6, 2013, 1:55 PM
Post edited by 2teez (Novice) on Jul 6, 2013, 2:07 PM


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

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