Perl Language File I/O (reading and writing files)

30% OFF - 9th Anniversary discount on Entity Framework Extensions until December 15 with code: ZZZANNIVERSARY9


>Write (trunc). Will overwrite existing files. Creates a new file if no file was found
>>Write (append). Will not overwrite files but append new content at the end of it. Will also create a file if used for opening a non existing file.
<Read. Opens the file in read only mode.
+<Read / Write. Will not create or truncate the file.
+>Read / Write (trunc). Will create and truncate the file.
+>>Read / Write (append). Will create but not truncate the file.


chomp is often used when reading from a file. By default it trims the newline character, although for its full functionality refer to the perldocs.

Beware of the difference between characters and bytes: Not all encodings - especially UTF-8 - use 1-byte-characters. While this is handled pretty much flawlessly by PerlIO, there is one potential pitfall of note:

  • read uses characters for its length and offset parameters
  • seek and tell always use bytes for positioning

So don't use arithmetics based on these mixed values. Instead use e.g. Encode::encode('utf8',$value_by_read) to get the octets(bytes) from a readresult, whose count you can then use with tell and seek.

Got any Perl Language Question?