Read perl file into array
Find centralized, trusted content and collaborate around the technologies you use most. Connect and share knowledge within a single location that is structured and easy to search.
I am currently reading a file and storing the data in an array named lines. Then, I loop through this array using a for loop and inside the loop I match on certain values:. Then you can get the count of filtered lines using scalar , which forces scalar that is, single value context on the interpretation of the array, in this case returning a count.
Use Tie::File. It loads the file into an array, which you can manipulate using array operations. When you untie the file, its components will be saved back in the file. You could also use the File::Slurp module, which is convenient. If you're new to Perl, take a look at the map and grep operators, which are handy for processing lists. Actually, it's a superior alternative. Stack Overflow for Teams — Collaborate and share knowledge with a private group.
Create a free Team What is Teams? Collectives on Stack Overflow. Learn more. Collectives on Stack Overflow. Learn more. How can I read the lines of a file into an array in Perl? Ask Question.
Asked 12 years, 1 month ago. Active 7 years, 7 months ago. Viewed 53k times. I have a file named test. Improve this question. Nathan Campos Nathan Campos Add a comment.
Active Oldest Votes. Improve this answer. Corey Corey 1, 9 9 silver badges 12 12 bronze badges. You should check if file was opened successfully. Or use autodie; — Ivan Nevostruev. Ivan Nevostruev Ivan Nevostruev Thank you. When evaluated in list context, the diamond operator returns a list consisting of all the lines in the file in this case, assigning the result to an array supplies list context. The line terminator is retained, and can be removed by chomping:. Input record separator can be specified with -0 switch zero , not capital O.
It takes an octal or hexadecimal number as value. Any value or above will cause Perl to slurp files, but by convention, the value used for this purpose is Reading a file's content into a variable Path::Tiny Using the idiom from The Manual Way opens new window several times in a script soon gets tedious so you might want to try a module.
0コメント