Perl slurp file into variable




















This is what we have in the data. So the read-line operator will read the file up-till the first time it encounters undef in the file. That never happens so it reads till the end of the file. This is what is called slurp mode , because of the sound the file makes when we read it.

In case you are wondering about the regex part here is the quick recap provided by J. Bismarck Fuentes. It will impact even third-party modules used in our application. That is certainly not good. For this we needed an enclosing block, so we added a pair of curly braces around the code-snippet dealing with the file. Creating a slurp function In the third iteration of the code, we create a separate function called slurp that will get the name of the file and return the content as a single string.

This allows us to hide the code-snippet at the end of the program or even in a separate file. It also makes it reusable, so instead of copying it to other places where we might need the same functionality we can just call the slurp function. This makes the main body of our code much nicer. Here, another global variable ARGV is localized to simulate the same process used when starting a perl script with parameters.

The sub has no explicit error handling, which is bad practice! If an error occurs while reading the file, you will receive undef as return value, as opposed to an empty string from an empty file. Another disadvantage of the last code is the fact that you cannot use PerlIO for different file encodings—you always get raw bytes.

Don't use it. Although it has been around for a long time and is still the module most programmers will suggest, it is broken and not likely to be fixed opens new window.

Active Oldest Votes. Improve this answer. See search. It is not google friendly : — Miroslav Popov. Is it correct? Perls is not. We have to read the unwritten. Quentin Quentin k gold badges silver badges bronze badges.

I disagree with loading a module merely to open and read a file. Being able to open and read files is too fundamental an operation not to understand very, very well. I disagree with endlessly writing the same five lines of code over and over when one plus a module will do. It's not even a standard module.

That's what dependancies in whatever you generate Makefiles from are for. Daniel Martin Daniel Martin But why the hating on CPAN modules?



0コメント

  • 1000 / 1000