Open a file in perl for reading




















There are a number of different ways of reading a file. The example below reads one line from the file and stores it in the scalar. If there was an error or the filehandle is at end of the file, then it returns undef. On the success of file reading, the function returns the number of bytes read, zero at end of file, or undef if there was an error.

Example: File. Give a warning When filehandle could not be assigned a valid file pointer it just prints warning message using warn function and keeps running. Skip to content. Change Language. Related Articles. Control Flow. OOP Concepts. Regular Expressions. File Handling. CGI Programming. Table of Contents. By signing up, you agree to our Terms of Use and Privacy Policy.

Forgot Password? This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy.

Perl open By Shobha Shivakumar. Popular Course in this category. Course Price View Course. Free Software Development Course. Login details for this Free course will be emailed to you.

Reading more than one line Once we know how to read one line we can go ahead and put the readline call in the condition of a while loop. If that line has anything in it, that will evaluate to true.

After we read the last line, in the next iteration the readline operator will return undef which is false. The while-loop will terminate. An edge-case There is an edge-case though when the very last line has a single 0 in it, without a trailing newline. The above code would evaluate that line to false and the loop would not be executed.

Fortunately, Perl is actually cheating here. For example when the whole job of your script is to parse that file. What if this is an optional configuration file? If you can read it you change some settings, if you cannot read you just use the defaults. In that case the second solution might be a better way to write your code.

If it is true we go ahead and read the content of the file. If it failed we give a warning using the built-in warn function but don't throw an exception.



0コメント

  • 1000 / 1000