PERL Commands

🐪 Perl Commands – File Operations

TopicQuestionAnswer
PerlRun scriptperl script.pl
PerlRun with warningsperl -w script.pl
PerlCheck syntaxperl -c script.pl
PerlRun one-linerperl -e 'print "Hello\n";'
PerlRun with modulesperl -M<Module> script.pl
PerlRun in place editperl -pi -e 's/old/new/g' file.txt
PerlPrint line numbersperl -ne 'print "$. $_"' file.txt
PerlFile is emptyif (-z "file.txt")
PerlFile existsif (-e "file.txt")
PerlFile readableif (-r "file.txt")
PerlFile writableif (-w "file.txt")
PerlFile executableif (-x "file.txt")
PerlIs directoryif (-d "path")
PerlIs fileif (-f "file.txt")
PerlIs symlinkif (-l "link")
PerlGet file sizemy $size = -s "file.txt";
PerlGet file age (days)my $age = -M "file.txt";
PerlGet modification timemy $mtime = (stat "file.txt")[9];
PerlOpen for readingopen(my $fh, '<', 'file.txt');
PerlOpen for writingopen(my $fh, '>', 'file.txt');
PerlOpen for appendingopen(my $fh, '>>', 'file.txt');
PerlOpen with error checkopen(my $fh, '<', 'file') or die "Cannot open: $!";
PerlClose fileclose($fh);
PerlRead linemy $line = <$fh>;
PerlRead all linesmy @lines = <$fh>;
PerlRead file line by linewhile (my $line = <$fh>) { }
PerlRead into arraymy @lines = <$fh>;
PerlWrite to fileprint $fh "text\n";
PerlPrint to STDOUTprint "text\n";
PerlPrint to STDERRprint STDERR "error\n";
PerlPrintf formattingprintf("Value: %d\n", $number);
PerlDie with errordie "Error: $!\n";
PerlWarn with messagewarn "Warning: something\n";
PerlSlurp filemy $content = do { local $/; <$fh> };
PerlRemove fileunlink('file.txt');
PerlRename filerename('old.txt', 'new.txt');
PerlCopy fileuse File::Copy; copy('src', 'dst');
PerlMove fileuse File::Copy; move('src', 'dst');

🔤 Perl Commands – String & Regex

TopicQuestionAnswer
PerlSearch and replace$line =~ s/old/new/g
PerlReplace case insensitive$line =~ s/old/new/gi
PerlReplace first occurrence$line =~ s/old/new/
PerlMatch patternif ($line =~ /pattern/)
PerlNegate matchif ($line !~ /pattern/)
PerlMatch case insensitiveif ($line =~ /pattern/i)
PerlMatch with captureif ($line =~ /(\d+)/) { my $num = $1; }
PerlGlobal matchmy @matches = $line =~ /pattern/g
PerlExecute with backticksmy $date = \date`;`
PerlExecute with systemsystem("ls -l");
PerlExecute with qxmy @array = qx(ls);
PerlGet exit codemy $exit = $? >> 8;
PerlSplit by spacesmy @words = split(/ /, $str);
PerlSplit by commasmy @fruits = split(/,/, $text);
PerlSplit by whitespacemy @words = split(/\s+/, $str);
PerlSplit with limitmy @parts = split(/,/, $str, 3);
PerlJoin arraymy $string = join(",", @array);
PerlString concatenationmy $result = $str1 . $str2;
PerlString repeatmy $repeated = $str x 3;
PerlString lengthmy $len = length($string);
PerlSubstringmy $sub = substr($string, $start, $len);
PerlIndex of substringmy $pos = index($string, $substring);
PerlLast indexmy $pos = rindex($string, $substring);
PerlUppercasemy $upper = uc($string);
PerlLowercasemy $lower = lc($string);
PerlUppercase firstmy $ucfirst = ucfirst($string);
PerlLowercase firstmy $lcfirst = lcfirst($string);
PerlTrim whitespace$string =~ s/^\s+|\s+$//g;
PerlTrim left$string =~ s/^\s+//;
PerlTrim right$string =~ s/\s+$//;
PerlCheck if containsif (index($string, $substring) != -1)
PerlString compareif ($str1 eq $str2)
PerlString not equalif ($str1 ne $str2)
PerlString less thanif ($str1 lt $str2)
PerlString greater thanif ($str1 gt $str2)
PerlNumeric compareif ($num1 == $num2)
PerlNot equal numericif ($num1 != $num2)
PerlLess thanif ($num1 < $num2)
PerlGreater thanif ($num1 > $num2)
PerlChomp newlinechomp($line);
PerlChop last characterchop($string);
PerlReverse stringmy $reversed = reverse($string);

🐪 Perl Commands – Arrays & Hashes

TopicQuestionAnswer
PerlPush to arraypush(@array, $element);
PerlPush multiplepush(@array, $el1, $el2);
PerlPop from arraymy $last = pop(@array);
PerlShift from arraymy $first = shift(@array);
PerlUnshift to arrayunshift(@array, $element);
PerlGet array lengthmy $length = scalar(@array);
PerlArray sizemy $size = $#array + 1;
PerlLast indexmy $last_idx = $#array;
PerlReverse arraymy @reversed = reverse(@array);
PerlSort arraymy @sorted = sort(@array);
PerlSort numericallymy @sorted = sort {$a <=> $b} @array;
PerlSort descendingmy @sorted = sort {$b <=> $a} @array;
PerlSort by lengthmy @sorted = sort {length($a) <=> length($b)} @array;
PerlCheck if in arrayif (grep {$_ eq $item} @array)
PerlFilter arraymy @filtered = grep {$_ > 10} @array;
PerlMap arraymy @doubled = map {$_ * 2} @array;
PerlArray slicemy @slice = @array[0..4];
PerlJoin arraymy $string = join(",", @array);
PerlCreate hashmy %hash = (key1 => 'value1', key2 => 'value2');
PerlAccess hash valuemy $value = $hash{key};
PerlSet hash value$hash{key} = 'value';
PerlCheck key existsif (exists $hash{key})
PerlCheck defined valueif (defined $hash{key})
PerlDelete hash keydelete $hash{key};
PerlGet all keysmy @keys = keys(%hash);
PerlGet all valuesmy @values = values(%hash);
PerlGet key-value pairsmy %copy = %hash;
PerlIterate hashwhile (my ($key, $value) = each %hash) { }
PerlIterate keysforeach my $key (keys %hash) { }
PerlHash sizemy $size = scalar(keys %hash);
PerlClear hash%hash = ();
PerlMerge hashesmy %merged = (%hash1, %hash2);

🐪 Perl Commands – Control Structures

TopicQuestionAnswer
PerlFor loopfor (my $i = 0; $i < 10; $i++) { }
PerlFor each loopforeach my $item (@array) { }
PerlFor each with indexfor my $i (0..$#array) { }
PerlWhile loopwhile (condition) { }
PerlUntil loopuntil (condition) { }
PerlDo-whiledo { } while (condition);
PerlLoop with nextnext; (continue)
PerlLoop with lastlast; (break)
PerlLoop with redoredo;
PerlIf statementif (condition) { }
PerlIf-elseif (condition) { } else { }
PerlIf-elsif-elseif (cond1) { } elsif (cond2) { } else { }
PerlUnless statementunless (condition) { }
PerlPostfix ifprint "yes" if $condition;
PerlPostfix unlessprint "no" unless $condition;
PerlTernary operatormy $result = $condition ? $true : $false;
PerlLogical ANDif ($cond1 && $cond2)
PerlLogical ORif ($cond1 || $cond2)
PerlLogical NOTif (!$condition)
PerlLogical and (low precedence)open my $fh, '<', $file and print "opened";
PerlLogical or (low precedence)open my $fh, '<', $file or die "Failed: $!";
PerlDefined-or operatormy $val = $var // "default";

🐪 Perl Commands – Subroutines & Modules

TopicQuestionAnswer
PerlDefine subroutinesub name { my ($arg1, $arg2) = @_; }
PerlCall subroutinename($arg1, $arg2);
PerlReturn from subreturn $value;
PerlReturn multiplereturn ($val1, $val2);
PerlSubroutine prototypesub name ($$$) { }
PerlAnonymous subroutinemy $sub = sub { };
PerlReference to submy $ref = \&name;
PerlCall sub reference$ref->($arg);
PerlUse strictuse strict;
PerlUse warningsuse warnings;
PerlUse moduleuse Module::Name;
PerlRequire modulerequire Module::Name;
PerlImport functionsuse Module qw(func1 func2);
PerlImport alluse Module ':all';
PerlNo importuse Module ();
PerlPackage declarationpackage MyPackage;
PerlGet command line argsmy $arg = $ARGV[0];
PerlAll CLI argumentsmy @args = @ARGV;
PerlNumber of argumentsmy $count = @ARGV;
PerlEnvironment variablemy $value = $ENV{VAR_NAME};
PerlSet environment$ENV{VAR_NAME} = 'value';
PerlProcess IDmy $pid = $$;
PerlProgram namemy $name = $0;

🐪 Perl Commands – Advanced Features

TopicQuestionAnswer
PerlCurrent directoryuse Cwd; my $dir = getcwd();
PerlChange directorychdir('/path/to/dir');
PerlList directoryopendir(my $dh, '.'); my @files = readdir($dh);
PerlClose directoryclosedir($dh);
PerlMake directorymkdir('dirname', 0755);
PerlRemove directoryrmdir('dirname');
PerlGet current timemy $time = time();
PerlFormat timeuse POSIX; strftime("%Y-%m-%d", localtime());
PerlSleep secondssleep(5);
PerlSleep microsecondsuse Time::HiRes; usleep(1000);
PerlGenerate randommy $rand = int(rand(100));
PerlSeed randomsrand(42);
PerlRound numberuse POSIX; my $rounded = floor($num);
PerlCeilinguse POSIX; my $ceil = ceil($num);
PerlAbsolute valuemy $abs = abs($num);
PerlSquare rootmy $sqrt = sqrt($num);
PerlPowermy $pow = $base ** $exp;
PerlCreate referencemy $ref = \$scalar;
PerlArray referencemy $aref = \@array;
PerlHash referencemy $href = \%hash;
PerlDereference scalarmy $val = $$ref;
PerlDereference arraymy @arr = @$aref;
PerlDereference hashmy %h = %$href;
PerlAnonymous arraymy $aref = [1, 2, 3];
PerlAnonymous hashmy $href = {key => 'value'};
PerlEval for exceptionseval { risky_code(); }; if ($@) { }
PerlDie with exceptiondie "Error: $!";

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top