Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

Re: Loading a part of the file to array using Tie::File

by kcott (Archbishop)
on Nov 24, 2017 at 00:02 UTC ( [id://1204180]=note: print w/replies, xml ) Need Help??


in reply to Loading a part of the file to array using Tie::File

G'day ansh007,

Welcome to the Monastery.

Take a look at "perlop: Range Operators" and the eof function. Your "from line number 100 till end" can be written in Perl as "100 .. eof".

Given this file:

$ cat XXX A B C D E

And an alias I use frequently:

$ alias perle alias perle='perl -Mstrict -Mwarnings -Mautodie=:all -E'

You can read from line 3 to the end like this:

$ perle 'open my $fh, "<", "XXX"; while (<$fh>) { print if 3 .. eof }' C D E

That also works with a literal line number instead of eof. For example, to print lines at the start, or in the middle:

$ perle 'open my $fh, "<", "XXX"; while (<$fh>) { print if 1 .. 3 }' A B C
$ perle 'open my $fh, "<", "XXX"; while (<$fh>) { print if 2 .. 4 }' B C D

For those last two, once you've read all the wanted lines, you can exit the while loop early with the last function.

See also: open for a better way to open files; the pragma index for links to strict, warnings and autodie (you should always use the first two; I highly recommend the third for simple I/O error checking); and, if you're unfamiliar with the "-M" and "-E" switches I've used, perlrun.

— Ken

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1204180]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others meditating upon the Monastery: (4)
As of 2024-04-19 14:09 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found