Category: "Perl"
Perl file open details
June 18th, 2019There are several ways to open files in Perl and it seems that there are many opinions on the best way to do so. I've looked into it a bit and I believe that I'm going to use the three-argument version of open going forward.
open (my $filename_fh, '<', $filename);
As stated in the linked page, benefits include:
- Perl will open files even if they contain file operation (< > |) characters
- The scalar file handle ends in _fh so it should be obvious it is a file handle everywhere
- The file handle should be meaningful
- The file handle will be cleaned up automatically if it goes out of scope
Execute a Perl code without ".pl" extension
July 28th, 2016How to execute perl without having to type the .pl extension
For Windows you'll need to add ";.pl" to the PATHEXT environment variable. (given that the .pl extension is associated with the perl executable, which is always the case with a normal Active Perl installation.)
How to recursively process files through directories
July 27th, 2016use File::Find;
sub eachFile {
my $filename = $_;
my $fullpath = $File::Find::name;
#remember that File::Find changes your CWD,
#so you can call open with just $_
if (-e $filename) { print "$filename exists!\n"; }
}
find (\&eachFile, "mydir/");How to process a multiline string line at a time
July 27th, 2016foreach (split(/\n/, $str)) {
if (/START/../END/) {
next if /START/ || /END/;
print;
}
}
Perl Search and Replace in files
July 6th, 2014Replace all occurrences of “oldstring” with “newstring” in all files (no recursion):
perl -pi -e 's/oldstring/newstring/g' *
Replace all occurrences of “oldstring” with “newstring” in all HTML files recursively:
perl -pi -e 's/oldstring/newstring/g' `find ./ -name *.html`
Replace all occurrences of “oldstring” with “newstring” in all files recursively:
perl -pi -e 's/oldstring/newstring/g' `grep -irl oldstring *`
Replace all occurrences of “oldstring” with “newstring” in all files recursively, excluding .svn directories:
perl -pi -e 's/oldstring/newstring/g' `grep -irl oldstring * | grep -v .svn'
Taken from this blog which seems to no longer be active.
