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

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Parameters

ModeExplaination
>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.

Remarks

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?