Perl


Here Document

Create a string spread over several lines.
 
my $name = 'Bob';

my $message = << "END_MESSAGE"; # Double-quotes interpolate content
Dear $name,

This is your last chance. Be good.

Sincerely,
Santa
END_MESSAGE

Output:

Dear Bob,

This is your last chance. Be good.

Sincerely,
Santa

Note that the end-mark string following the text body e.g. 'END_MESSAGE' must exactly match its definition with no leading or trailing spaces.

Credit: Perl Maven - Here Documents

Capture a regex match in one line

my ($match) = "some string" =~ /(some).*/; 
print $match; # prints "some"

Get the script path

# C:\Foo\Bar\my_script.pl 
use strict; 
use warnings; 
use FindBin qw($Bin); 

print "My script lives in $Bin\n"; # My script lives in C:/Foo/Bar

Note that there is no trailing slash, and Windows back-slashes '\' are converted to forward slashes '/'

Backticks, system() and exec()

  • exec(cmd)
    • executes command 
    • never returns
    • returns false if cmd not found
  • system(cmd)
    • executes command 
    • continues execution
    • returns exit status of command
  • `cmd` (backticks)
    • executes command
    • continues execution
    • returns STDOUT
      • list context: list of lines from output
      • scalar context: single string joined with newlines
    • qx// is equivalent quote
  • open(cmd)
    • command runs simultaneously with script
    • can read STDOUT/STDERR and write STDIN
    • Modules that might help:
      • IPC::Open2
      • IPC::Open3
      • IPC::Run
      • Win32::Process::Create