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";
}
NOTE:
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:
- use these pragma: warnings and strict
- use lexically scoped file-handles and use 3 -argument open function like
open my $fh, '<', "file_to_open" or die "can't open file: $!";
- use a while loop, to walk through a file, step-wise like:
while(<$fh>){
...
}
- close all opened file handles
- 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
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.