Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options

Re: reading the 5th element from file doesn't work.

by 2teez (Priest)
on Apr 24, 2013 at 05:38 UTC ( #1030282=note: print w/replies, xml ) Need Help??

in reply to reading the 5th element from file doesn't work.

Hi singho,
There are several things wrong here.
1. According to your post title, do you what the 5th Element of the whole file, or each line in the file?
If your intention is the 5th Element of the whole file, then do this:

my @string; open(SYSLOG, "/tmp/log100lines") or die "Can't open file: $!\n"; foreach my $line (<SYSLOG>) { chomp $line; push @string, $line } print $string[4],$/;
2. But it seem, to me you want the 5th element of each line, which in that case you need do this:
open(SYSLOG, "/tmp/log100lines") or die "Can't open file: $!\n"; foreach my $line (<SYSLOG>) { chomp $line; my @string = split(/ /, $line); ## remove the function join print "$string[4]\n"; }
a.) The scope of the array variable "@string" in the both cases,
b.) In the second script, you don't need the function join, because it Joins the separate strings of LIST into a single string with fields separated by the value of EXPR which in your case is ',', so your 5th element of each line has an uninitialized value.

That been said, there are a number of things, I think one should take note:
  1. use these pragma: warnings and strict
  2. use lexically scoped file-handles and use 3 -argument open function like
    open my $fh, '<', "file_to_open" or die "can't open file: $!";
  3. use a while loop, to walk through a file, step-wise like:
    while(<$fh>){ ... }
  4. close all opened file handles
  5. Please, also check your shebang line

If you tell me, I'll forget.
If you show me, I'll remember.
if you involve me, I'll understand.
--- Author unknown to me

Replies are listed 'Best First'.
Re^2: reading the 5th element from file doesn't work.
by singho (Novice) on Apr 24, 2013 at 08:54 UTC
    Thanks a lot for your help a explantion, i ended up using join, since the above with just split failed eariler, may be i missed something before. I tried using the above code it worked neatly. Thanks a lot.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1030282]
[Discipulus]: [OT] if i have an svg image (a map of italian provinces) like this one in which way i need to interact with it to have a geochart?
[Corion]: I haven't found a good way to plot stuff into country maps... Maybe one of the demos of D3.js has something usable?
[Discipulus]: i need to use css to get and colorize various different IDs?
[Corion]: I haven't used it, but http://datamaps. looks promising

How do I use this? | Other CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (13)
As of 2017-03-23 09:18 GMT
Find Nodes?
    Voting Booth?
    Should Pluto Get Its Planethood Back?

    Results (285 votes). Check out past polls.