| 1 | package Acme::CPANModules::ReadingFilesBackward; | ||
| 2 | |||
| 3 | 1 | our $AUTHORITY = 'cpan:PERLANCAR'; # AUTHORITY | |
| 4 | 1 | our $DATE = '2020-03-01'; # DATE | |
| 5 | 1 | our $DIST = 'Acme-CPANModules-ReadingFilesBackward'; # DIST | |
| 6 | 1 | our $VERSION = '0.002'; # VERSION | |
| 7 | |||
| 8 | 1 | ▶ | use strict; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 9 | 1 | ▶ | use Acme::CPANModulesUtil::Misc; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 10 | |||
| 11 | 1 | our $LIST = { | |
| 12 | summary => 'Reading files backward (in reverse)', | ||
| 13 | description => <<'_', | ||
| 14 | |||
| 15 | Probably the fastest way, if you are on a Unix system, is to use the **tac** | ||
| 16 | command, which can read a file line by line in reverse order, or paragraph by | ||
| 17 | paragraph, or character by character, or word by word, or by a custom separator | ||
| 18 | string or regular expression. Example for using it from Perl: | ||
| 19 | |||
| 20 | open my $fh, "tac /etc/passwd |"; | ||
| 21 | print while <$fh>; | ||
| 22 | |||
| 23 | Another convenient way is to use the Perl I/O layer <pm:PerlIO::reverse>. It | ||
| 24 | only does line-by-line reversing, but you can use the regular Perl API. You | ||
| 25 | don't even have to `use` the module explicitly (but of course you have to get it | ||
| 26 | installed first): | ||
| 27 | |||
| 28 | open my $fh, "<:reverse", "/etc/passwd"; | ||
| 29 | print while <$fh>; | ||
| 30 | |||
| 31 | If your file is small (fits in your system's memory), you can also slurp the | ||
| 32 | file contents first into an array (either line by line, or paragraph by | ||
| 33 | paragraph, or what have you) and then simply `reverse` the array: | ||
| 34 | |||
| 35 | open my $fh, "<", "/etc/passwd"; | ||
| 36 | my @lines = <$fh>; | ||
| 37 | print for reverse @lines; | ||
| 38 | |||
| 39 | If the above solutions do not fit your needs, there are also these modules which | ||
| 40 | can help: <pm:File::ReadBackward>, <pm:File::Bidirectional>. File::ReadBackward | ||
| 41 | is slightly faster than File::Bidirectional, but File::Bidirectional can read | ||
| 42 | forward as well as backward. I now simply prefer PerlIO::reverse because I don't | ||
| 43 | have to use a custom API for reading files. | ||
| 44 | |||
| 45 | _ | ||
| 46 | 'x.app.cpanmodules.show_entries' => 0, | ||
| 47 | }; | ||
| 48 | |||
| 49 | 1 | Acme::CPANModulesUtil::Misc::populate_entries_from_module_links_in_description; | |
| 50 | |||
| 51 | 1 | 1; | |
| 52 | # ABSTRACT: Reading files backward (in reverse) | ||
| 53 | |||
| 54 | __END__ | ||