Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Built-in Functions

PetaPerl implements the Perl 5 built-in function library. This document lists all implemented functions, organized by category.

Legend:

  • ✅ Fully implemented
  • ⚠️ Partially implemented
  • ❌ Not yet implemented

I/O Functions

FunctionStatusDescription
printPrint to filehandle or STDOUT
sayPrint with newline
printfFormatted print
sprintfFormatted string
print "Hello\n";
print $fh "data\n";
say "Hello";                    # Adds newline
printf "%d items\n", $count;
my $str = sprintf "%05d", $num;

File Operations

FunctionStatusDescription
openOpen file or pipe
closeClose filehandle
readRead fixed-length data
sysreadSystem-level read
syswriteSystem-level write
readlineRead line(s) from filehandle
getcRead single character
eofTest for end-of-file
seekPosition filehandle
tellGet filehandle position
filenoGet file descriptor number
binmodeSet binary mode
selectSet default filehandle
writeWrite formatted record
open my $fh, '<', $filename or die $!;
my $data;
read $fh, $data, 1024;          # Read 1024 bytes
my $line = readline($fh);       # or <$fh>
my $char = getc($fh);
seek $fh, 0, 0;                 # Rewind to start
my $pos = tell $fh;
close $fh;

Directory Operations

FunctionStatusDescription
opendirOpen directory handle
readdirRead directory entry
closedirClose directory handle
rewinddirReset directory handle
seekdirPosition directory handle
telldirGet directory position
mkdirCreate directory
rmdirRemove directory
chdirChange working directory
opendir my $dh, $dir or die $!;
my @entries = readdir $dh;
closedir $dh;

mkdir "newdir", 0755 or die $!;
rmdir "olddir";
chdir "/tmp";

File System Operations

FunctionStatusDescription
unlinkDelete files
renameRename file
linkCreate hard link
symlinkCreate symbolic link
readlinkRead symbolic link
chmodChange file permissions
chownChange file owner/group
utimeChange access/modification times
truncateTruncate file to length
statGet file status
lstatGet file status (no link follow)
globFile name expansion
unlink "file.txt" or die $!;
rename "old.txt", "new.txt";
link "source", "link";
symlink "target", "symlink";
my $target = readlink "symlink";
chmod 0644, @files;
chown $uid, $gid, @files;
utime $atime, $mtime, @files;
truncate $fh, $length;
my @info = stat $file;
my @info = lstat $symlink;      # Doesn't follow symlink
my @files = glob "*.txt";

String Functions

FunctionStatusDescription
lengthString/array length
substrExtract/replace substring
indexFind substring position
rindexFind substring (reverse)
chrNumber to character
ordCharacter to number
lcLowercase string
ucUppercase string
lcfirstLowercase first char
ucfirstUppercase first char
quotemetaQuote metacharacters
chopRemove last character
chompRemove line ending
hexHex string to number
octOctal string to number
packPack values into binary string
unpackUnpack binary string
vecBit vector access
my $len = length $str;
my $sub = substr $str, 0, 5;    # First 5 chars
substr($str, 7, 5) = "replace";  # Lvalue substr
my $pos = index $str, "find";
my $rpos = rindex $str, "last";

my $char = chr(65);              # "A"
my $code = ord("A");             # 65

my $lower = lc "HELLO";          # "hello"
my $upper = uc "hello";          # "HELLO"
my $cap = ucfirst "hello";       # "Hello"

chomp $line;                     # Remove \n if present
chop $str;                       # Remove last char
my $quoted = quotemeta '.*';     # '\\.\\\*'

my $num = hex "FF";              # 255
my $num = oct "377";             # 255

Lvalue substr: substr can be used as assignment target.

substr($str, 0, 3) = "New";      # Replace first 3 chars

Array Functions

FunctionStatusDescription
pushAppend to array
popRemove last element
shiftRemove first element
unshiftPrepend to array
spliceRemove/replace array elements
joinJoin array with separator
splitSplit string into array
reverseReverse list/string
sortSort list
grepFilter list
mapTransform list
push @arr, $val;
push @arr, @more;
my $last = pop @arr;
my $first = shift @arr;
unshift @arr, $val;

splice @arr, $offset, $length, @replacement;
my $str = join ",", @arr;
my @parts = split /,/, $str;
my @reversed = reverse @arr;
my @sorted = sort @arr;
my @sorted = sort { $a <=> $b } @numbers;
my @filtered = grep { $_ > 10 } @numbers;
my @doubled = map { $_ * 2 } @numbers;

Parallel execution: map, grep, and simple for loops may execute in parallel when safe.

Hash Functions

FunctionStatusDescription
keysGet hash keys
valuesGet hash values
eachIterate key-value pairs
existsCheck if key exists
deleteRemove hash key
my @keys = keys %hash;
my @vals = values %hash;
while (my ($k, $v) = each %hash) { ... }
if (exists $hash{key}) { ... }
my $removed = delete $hash{key};

Context sensitivity: keys and values return list in list context, count in scalar context.

my $count = keys %hash;          # Number of keys
my @all_keys = keys %hash;       # All keys

Math Functions

FunctionStatusDescription
absAbsolute value
intInteger truncation
sqrtSquare root
sinSine
cosCosine
expe raised to power
logNatural logarithm
atan2Arc tangent of y/x
randRandom number
srandSeed random number generator
my $abs = abs -5;                # 5
my $int = int 3.7;               # 3
my $sqrt = sqrt 16;              # 4
my $sin = sin $angle;
my $cos = cos $angle;
my $exp = exp 1;                 # e
my $log = log 10;
my $atan = atan2 $y, $x;
my $rand = rand 10;              # 0 to <10
srand 42;                        # Seed with specific value

Type and Reference Functions

FunctionStatusDescription
refGet reference type
blessBless reference into package
definedTest if defined
undefUndefine variable
scalarForce scalar context
my $type = ref $value;           # 'ARRAY', 'HASH', 'CODE', etc.
my $obj = bless {}, 'MyClass';
my $obj = bless $ref, 'MyClass';
if (defined $var) { ... }
undef $var;                      # Set to undef
my $count = scalar @arr;         # Force scalar context

Control and Introspection

FunctionStatusDescription
callerGet caller information
wantarrayGet calling context
prototypeGet subroutine prototype
posGet/set regex position
studyOptimize regex matching
resetReset variables
my ($package, $file, $line) = caller;
my ($pkg, $file, $line, $sub) = caller(1);
if (wantarray) {
    return @list;
} else {
    return $scalar;
}
my $proto = prototype \&mysub;
my $pos = pos $str;
study $str;                      # Optimize for repeated regex
reset;                           # Reset ?? searches

Process and System

FunctionStatusDescription
dieRaise exception
warnPrint warning
exitExit program
systemExecute external command
execExecute and replace process
forkFork child process
waitWait for child
waitpidWait for specific child
sleepSleep for seconds
timeGet current Unix time
timesGet process times
localtimeConvert time to local
gmtimeConvert time to GMT
getloginGet login name
die "Error: $!" if $error;
warn "Warning message";
exit 0;

my $status = system "ls", "-l";
exec "command", @args;           # No return if success
my $pid = fork;
if ($pid == 0) {
    # Child process
} else {
    # Parent process
}
wait;                            # Wait for any child
waitpid $pid, 0;                 # Wait for specific child

sleep 5;                         # Sleep 5 seconds
my $now = time;
my @times = times;               # (user, system, cuser, csystem)
my @lt = localtime time;
my @gmt = gmtime time;
my $user = getlogin;

User and Group Database

All user/group database functions are implemented:

FunctionStatusDescription
getpwnamGet password entry by name
getpwuidGet password entry by UID
getpwentGet next password entry
setpwentReset password iteration
endpwentEnd password iteration
getgrnamGet group entry by name
getgrgidGet group entry by GID
getgrentGet next group entry
setgrentReset group iteration
endgrentEnd group iteration
my @pwinfo = getpwnam "username";
my @pwinfo = getpwuid $uid;
while (my @entry = getpwent) { ... }
endpwent;

my @grinfo = getgrnam "groupname";
my @grinfo = getgrgid $gid;

Network Database

All network database functions are implemented:

FunctionStatusDescription
gethostbynameGet host by name
gethostbyaddrGet host by address
gethostentGet next host entry
sethostentReset host iteration
endhostentEnd host iteration
getnetbynameGet network by name
getnetbyaddrGet network by address
getnetentGet next network entry
setnetentReset network iteration
endnetentEnd network iteration
getprotobynameGet protocol by name
getprotobynumberGet protocol by number
getprotoentGet next protocol entry
setprotoentReset protocol iteration
endprotoentEnd protocol iteration
getservbynameGet service by name
getservbyportGet service by port
getserventGet next service entry
setserventReset service iteration
endserventEnd service iteration
my @host = gethostbyname "example.com";
my @net = getnetbyname "loopback";
my @proto = getprotobyname "tcp";
my @serv = getservbyname "http", "tcp";

Tie Mechanism

FunctionStatusDescription
tie⚠️Bind variable to object (stub — returns undef)
tied⚠️Get tied object (stub — returns undef)
untie⚠️Unbind variable (stub — no-op)

The functions are recognized and callable but do not dispatch to tie class methods. Modules depending on tie (e.g., Tie::File) will not function correctly.

Formats (Legacy)

FunctionStatusDescription
formline⚠️Format line (stub)
write⚠️Write formatted output (stub)

Perl formats are a legacy feature. The functions exist but the format output system is not implemented. Use printf/sprintf instead.

Socket Functions

All socket operations are implemented:

FunctionStatusDescription
socketCreate socket
socketpairCreate socket pair
bindBind socket to address
listenListen on socket
acceptAccept connection
connectConnect to remote
shutdownShut down socket
sendSend data
recvReceive data
getsockoptGet socket option
setsockoptSet socket option
getsocknameGet local address
getpeernameGet remote address

IPC Functions

FunctionStatusDescription
pipeCreate pipe
msgctlMessage queue control
msggetGet message queue
msgsndSend message
msgrcvReceive message
semctlSemaphore control
semgetGet semaphore set
semopSemaphore operations
shmctlShared memory control
shmgetGet shared memory
shmreadRead shared memory
shmwriteWrite shared memory

Known Limitations

Regular Expressions

  • qr// is fully implemented including precompiled pattern reuse
  • (?{code}) embedded code execution is implemented
  • Possessive quantifiers (*+, ++, ?+) are implemented
  • See Regular Expressions for remaining edge cases (self-referential captures, multi-char case folding)

Module System

  • use and require work for Pure Perl modules
  • XS modules are not supported (native reimplementations provided for common ones)
  • Some pragma effects may differ from perl5

Special Variables

  • Most special variables are populated ($^O, $^X, $], $^V, etc.)
  • Internals::SvREADONLY is not implemented

PetaPerl-Specific Notes

Constant Folding

PetaPerl performs compile-time constant folding for:

length("hello")      # Folded to 5 at compile time
substr("text", 0, 2) # Folded to "te"

Parallel Execution

These functions may execute in parallel when safe:

  • map - Parallel element transformation
  • grep - Parallel filtering
  • sort with pure comparison function

Parallelization requires:

  • No side effects in the callback
  • No shared mutable state
  • Array size above parallelization threshold

Performance

  • String functions use UTF-8 aware operations
  • Array operations minimize copying
  • Hash operations use optimized hash tables
  • Math functions map to CPU instructions when possible