🐪 Perl Commands – File Operations
| Topic | Question | Answer |
|---|---|---|
| Perl | Run script | perl script.pl |
| Perl | Run with warnings | perl -w script.pl |
| Perl | Check syntax | perl -c script.pl |
| Perl | Run one-liner | perl -e 'print "Hello\n";' |
| Perl | Run with modules | perl -M<Module> script.pl |
| Perl | Run in place edit | perl -pi -e 's/old/new/g' file.txt |
| Perl | Print line numbers | perl -ne 'print "$. $_"' file.txt |
| Perl | File is empty | if (-z "file.txt") |
| Perl | File exists | if (-e "file.txt") |
| Perl | File readable | if (-r "file.txt") |
| Perl | File writable | if (-w "file.txt") |
| Perl | File executable | if (-x "file.txt") |
| Perl | Is directory | if (-d "path") |
| Perl | Is file | if (-f "file.txt") |
| Perl | Is symlink | if (-l "link") |
| Perl | Get file size | my $size = -s "file.txt"; |
| Perl | Get file age (days) | my $age = -M "file.txt"; |
| Perl | Get modification time | my $mtime = (stat "file.txt")[9]; |
| Perl | Open for reading | open(my $fh, '<', 'file.txt'); |
| Perl | Open for writing | open(my $fh, '>', 'file.txt'); |
| Perl | Open for appending | open(my $fh, '>>', 'file.txt'); |
| Perl | Open with error check | open(my $fh, '<', 'file') or die "Cannot open: $!"; |
| Perl | Close file | close($fh); |
| Perl | Read line | my $line = <$fh>; |
| Perl | Read all lines | my @lines = <$fh>; |
| Perl | Read file line by line | while (my $line = <$fh>) { } |
| Perl | Read into array | my @lines = <$fh>; |
| Perl | Write to file | print $fh "text\n"; |
| Perl | Print to STDOUT | print "text\n"; |
| Perl | Print to STDERR | print STDERR "error\n"; |
| Perl | Printf formatting | printf("Value: %d\n", $number); |
| Perl | Die with error | die "Error: $!\n"; |
| Perl | Warn with message | warn "Warning: something\n"; |
| Perl | Slurp file | my $content = do { local $/; <$fh> }; |
| Perl | Remove file | unlink('file.txt'); |
| Perl | Rename file | rename('old.txt', 'new.txt'); |
| Perl | Copy file | use File::Copy; copy('src', 'dst'); |
| Perl | Move file | use File::Copy; move('src', 'dst'); |
🔤 Perl Commands – String & Regex
| Topic | Question | Answer |
|---|---|---|
| Perl | Search and replace | $line =~ s/old/new/g |
| Perl | Replace case insensitive | $line =~ s/old/new/gi |
| Perl | Replace first occurrence | $line =~ s/old/new/ |
| Perl | Match pattern | if ($line =~ /pattern/) |
| Perl | Negate match | if ($line !~ /pattern/) |
| Perl | Match case insensitive | if ($line =~ /pattern/i) |
| Perl | Match with capture | if ($line =~ /(\d+)/) { my $num = $1; } |
| Perl | Global match | my @matches = $line =~ /pattern/g |
| Perl | Execute with backticks | my $date = \date`;` |
| Perl | Execute with system | system("ls -l"); |
| Perl | Execute with qx | my @array = qx(ls); |
| Perl | Get exit code | my $exit = $? >> 8; |
| Perl | Split by spaces | my @words = split(/ /, $str); |
| Perl | Split by commas | my @fruits = split(/,/, $text); |
| Perl | Split by whitespace | my @words = split(/\s+/, $str); |
| Perl | Split with limit | my @parts = split(/,/, $str, 3); |
| Perl | Join array | my $string = join(",", @array); |
| Perl | String concatenation | my $result = $str1 . $str2; |
| Perl | String repeat | my $repeated = $str x 3; |
| Perl | String length | my $len = length($string); |
| Perl | Substring | my $sub = substr($string, $start, $len); |
| Perl | Index of substring | my $pos = index($string, $substring); |
| Perl | Last index | my $pos = rindex($string, $substring); |
| Perl | Uppercase | my $upper = uc($string); |
| Perl | Lowercase | my $lower = lc($string); |
| Perl | Uppercase first | my $ucfirst = ucfirst($string); |
| Perl | Lowercase first | my $lcfirst = lcfirst($string); |
| Perl | Trim whitespace | $string =~ s/^\s+|\s+$//g; |
| Perl | Trim left | $string =~ s/^\s+//; |
| Perl | Trim right | $string =~ s/\s+$//; |
| Perl | Check if contains | if (index($string, $substring) != -1) |
| Perl | String compare | if ($str1 eq $str2) |
| Perl | String not equal | if ($str1 ne $str2) |
| Perl | String less than | if ($str1 lt $str2) |
| Perl | String greater than | if ($str1 gt $str2) |
| Perl | Numeric compare | if ($num1 == $num2) |
| Perl | Not equal numeric | if ($num1 != $num2) |
| Perl | Less than | if ($num1 < $num2) |
| Perl | Greater than | if ($num1 > $num2) |
| Perl | Chomp newline | chomp($line); |
| Perl | Chop last character | chop($string); |
| Perl | Reverse string | my $reversed = reverse($string); |
🐪 Perl Commands – Arrays & Hashes
| Topic | Question | Answer |
|---|---|---|
| Perl | Push to array | push(@array, $element); |
| Perl | Push multiple | push(@array, $el1, $el2); |
| Perl | Pop from array | my $last = pop(@array); |
| Perl | Shift from array | my $first = shift(@array); |
| Perl | Unshift to array | unshift(@array, $element); |
| Perl | Get array length | my $length = scalar(@array); |
| Perl | Array size | my $size = $#array + 1; |
| Perl | Last index | my $last_idx = $#array; |
| Perl | Reverse array | my @reversed = reverse(@array); |
| Perl | Sort array | my @sorted = sort(@array); |
| Perl | Sort numerically | my @sorted = sort {$a <=> $b} @array; |
| Perl | Sort descending | my @sorted = sort {$b <=> $a} @array; |
| Perl | Sort by length | my @sorted = sort {length($a) <=> length($b)} @array; |
| Perl | Check if in array | if (grep {$_ eq $item} @array) |
| Perl | Filter array | my @filtered = grep {$_ > 10} @array; |
| Perl | Map array | my @doubled = map {$_ * 2} @array; |
| Perl | Array slice | my @slice = @array[0..4]; |
| Perl | Join array | my $string = join(",", @array); |
| Perl | Create hash | my %hash = (key1 => 'value1', key2 => 'value2'); |
| Perl | Access hash value | my $value = $hash{key}; |
| Perl | Set hash value | $hash{key} = 'value'; |
| Perl | Check key exists | if (exists $hash{key}) |
| Perl | Check defined value | if (defined $hash{key}) |
| Perl | Delete hash key | delete $hash{key}; |
| Perl | Get all keys | my @keys = keys(%hash); |
| Perl | Get all values | my @values = values(%hash); |
| Perl | Get key-value pairs | my %copy = %hash; |
| Perl | Iterate hash | while (my ($key, $value) = each %hash) { } |
| Perl | Iterate keys | foreach my $key (keys %hash) { } |
| Perl | Hash size | my $size = scalar(keys %hash); |
| Perl | Clear hash | %hash = (); |
| Perl | Merge hashes | my %merged = (%hash1, %hash2); |
🐪 Perl Commands – Control Structures
| Topic | Question | Answer |
|---|---|---|
| Perl | For loop | for (my $i = 0; $i < 10; $i++) { } |
| Perl | For each loop | foreach my $item (@array) { } |
| Perl | For each with index | for my $i (0..$#array) { } |
| Perl | While loop | while (condition) { } |
| Perl | Until loop | until (condition) { } |
| Perl | Do-while | do { } while (condition); |
| Perl | Loop with next | next; (continue) |
| Perl | Loop with last | last; (break) |
| Perl | Loop with redo | redo; |
| Perl | If statement | if (condition) { } |
| Perl | If-else | if (condition) { } else { } |
| Perl | If-elsif-else | if (cond1) { } elsif (cond2) { } else { } |
| Perl | Unless statement | unless (condition) { } |
| Perl | Postfix if | print "yes" if $condition; |
| Perl | Postfix unless | print "no" unless $condition; |
| Perl | Ternary operator | my $result = $condition ? $true : $false; |
| Perl | Logical AND | if ($cond1 && $cond2) |
| Perl | Logical OR | if ($cond1 || $cond2) |
| Perl | Logical NOT | if (!$condition) |
| Perl | Logical and (low precedence) | open my $fh, '<', $file and print "opened"; |
| Perl | Logical or (low precedence) | open my $fh, '<', $file or die "Failed: $!"; |
| Perl | Defined-or operator | my $val = $var // "default"; |
🐪 Perl Commands – Subroutines & Modules
| Topic | Question | Answer |
|---|---|---|
| Perl | Define subroutine | sub name { my ($arg1, $arg2) = @_; } |
| Perl | Call subroutine | name($arg1, $arg2); |
| Perl | Return from sub | return $value; |
| Perl | Return multiple | return ($val1, $val2); |
| Perl | Subroutine prototype | sub name ($$$) { } |
| Perl | Anonymous subroutine | my $sub = sub { }; |
| Perl | Reference to sub | my $ref = \&name; |
| Perl | Call sub reference | $ref->($arg); |
| Perl | Use strict | use strict; |
| Perl | Use warnings | use warnings; |
| Perl | Use module | use Module::Name; |
| Perl | Require module | require Module::Name; |
| Perl | Import functions | use Module qw(func1 func2); |
| Perl | Import all | use Module ':all'; |
| Perl | No import | use Module (); |
| Perl | Package declaration | package MyPackage; |
| Perl | Get command line args | my $arg = $ARGV[0]; |
| Perl | All CLI arguments | my @args = @ARGV; |
| Perl | Number of arguments | my $count = @ARGV; |
| Perl | Environment variable | my $value = $ENV{VAR_NAME}; |
| Perl | Set environment | $ENV{VAR_NAME} = 'value'; |
| Perl | Process ID | my $pid = $$; |
| Perl | Program name | my $name = $0; |
🐪 Perl Commands – Advanced Features
| Topic | Question | Answer |
|---|---|---|
| Perl | Current directory | use Cwd; my $dir = getcwd(); |
| Perl | Change directory | chdir('/path/to/dir'); |
| Perl | List directory | opendir(my $dh, '.'); my @files = readdir($dh); |
| Perl | Close directory | closedir($dh); |
| Perl | Make directory | mkdir('dirname', 0755); |
| Perl | Remove directory | rmdir('dirname'); |
| Perl | Get current time | my $time = time(); |
| Perl | Format time | use POSIX; strftime("%Y-%m-%d", localtime()); |
| Perl | Sleep seconds | sleep(5); |
| Perl | Sleep microseconds | use Time::HiRes; usleep(1000); |
| Perl | Generate random | my $rand = int(rand(100)); |
| Perl | Seed random | srand(42); |
| Perl | Round number | use POSIX; my $rounded = floor($num); |
| Perl | Ceiling | use POSIX; my $ceil = ceil($num); |
| Perl | Absolute value | my $abs = abs($num); |
| Perl | Square root | my $sqrt = sqrt($num); |
| Perl | Power | my $pow = $base ** $exp; |
| Perl | Create reference | my $ref = \$scalar; |
| Perl | Array reference | my $aref = \@array; |
| Perl | Hash reference | my $href = \%hash; |
| Perl | Dereference scalar | my $val = $$ref; |
| Perl | Dereference array | my @arr = @$aref; |
| Perl | Dereference hash | my %h = %$href; |
| Perl | Anonymous array | my $aref = [1, 2, 3]; |
| Perl | Anonymous hash | my $href = {key => 'value'}; |
| Perl | Eval for exceptions | eval { risky_code(); }; if ($@) { } |
| Perl | Die with exception | die "Error: $!"; |