Perl Built-ins Quick Reference
1. String Functions
length
Returns the length of a string.
my $str = "Hello, World!";
my $len = length($str);
print "Length: $len\n"; # Output: Length: 13
substr
Extracts a substring from a string.
my $str = "Hello, World!";
my $sub = substr($str, 0, 5);
print "Substring: $sub\n"; # Output: Substring: Hello
index
Returns the position of a substring within a string.
my $str = "Hello, World!";
my $pos = index($str, "World");
print "Position: $pos\n"; # Output: Position: 7
rindex
Returns the last position of a substring within a string.
my $str = "Hello, World! World!";
my $pos = rindex($str, "World");
print "Last Position: $pos\n"; # Output: Last Position: 14
uc
Converts a string to uppercase.
my $str = "Hello, World!";
my $uc_str = uc($str);
print "Uppercase: $uc_str\n"; # Output: Uppercase: HELLO, WORLD!
lc
Converts a string to lowercase.
my $str = "Hello, World!";
my $lc_str = lc($str);
print "Lowercase: $lc_str\n"; # Output: Lowercase: hello, world!
ucfirst
Converts the first character of a string to uppercase.
my $str = "hello, world!";
my $ucfirst_str = ucfirst($str);
print "Ucfirst: $ucfirst_str\n"; # Output: Ucfirst: Hello, world!
lcfirst
Converts the first character of a string to lowercase.
my $str = "Hello, World!";
my $lcfirst_str = lcfirst($str);
print "Lcfirst: $lcfirst_str\n"; # Output: Lcfirst: hello, World!
chomp
Removes the trailing newline from a string.
my $str = "Hello, World!\n";
chomp($str);
print "Chomped: $str\n"; # Output: Chomped: Hello, World!
chop
Removes the last character from a string.
my $str = "Hello, World!";
chop($str);
print "Chopped: $str\n"; # Output: Chopped: Hello, World
2. Array Functions
push
Adds one or more elements to the end of an array.
my @array = (1, 2, 3);
push @array, 4, 5;
print "Array: @array\n"; # Output: Array: 1 2 3 4 5
pop
Removes and returns the last element of an array.
my @array = (1, 2, 3);
my $last_element = pop @array;
print "Last Element: $last_element\n"; # Output: Last Element: 3
shift
Removes and returns the first element of an array.
my @array = (1, 2, 3);
my $first_element = shift @array;
print "First Element: $first_element\n"; # Output: First Element: 1
unshift
Adds one or more elements to the beginning of an array.
my @array = (2, 3);
unshift @array, 0, 1;
print "Array: @array\n"; # Output: Array: 0 1 2 3
splice
Adds or removes elements from an array.
my @array = (1, 2, 3, 4, 5);
splice @array, 2, 2, (6, 7);
print "Array: @array\n"; # Output: Array: 1 2 6 7 5
sort
Sorts an array.
my @array = (3, 1, 4, 1, 5, 9);
my @sorted_array = sort @array;
print "Sorted Array: @sorted_array\n"; # Output: Sorted Array: 1 1 3 4 5 9
reverse
Reverses an array or string.
my @array = (1, 2, 3);
my @reversed_array = reverse @array;
print "Reversed Array: @reversed_array\n"; # Output: Reversed Array: 3 2 1
join
Joins elements of an array into a string.
my @array = ("Hello", "World");
my $str = join(" ", @array);
print "Joined String: $str\n"; # Output: Joined String: Hello World
split
Splits a string into an array.
my $str = "Hello World";
my @array = split(" ", $str);
print "Array: @array\n"; # Output: Array: Hello World
3. Hash Functions
keys
Returns the keys of a hash.
my %hash = (a => 1, b => 2, c => 3);
my @keys = keys %hash;
print "Keys: @keys\n"; # Output: Keys: a b c
values
Returns the values of a hash.
my %hash = (a => 1, b => 2, c => 3);
my @values = values %hash;
print "Values: @values\n"; # Output: Values: 1 2 3
each
Iterates over key-value pairs in a hash.
my %hash = (a => 1, b => 2, c => 3);
while (my ($key, $value) = each %hash) {
print "$key => $value\n";
}
# Output:
# a => 1
# b => 2
# c => 3
exists
Checks if a key exists in a hash.
my %hash = (a => 1, b => 2, c => 3);
if (exists $hash{a}) {
print "Key 'a' exists\n"; # Output: Key 'a' exists
}
delete
Deletes a key-value pair from a hash.
my %hash = (a => 1, b => 2, c => 3);
delete $hash{b};
print "Hash after deletion: ", %hash, "\n"; # Output: Hash after deletion: a1c3
4. File Handling Functions
open
Opens a file.
open(my $fh, '<', 'file.txt') or die "Could not open file: $!";
close
Closes a file.
close($fh);
read
Reads from a file.
my $buffer;
read($fh, $buffer, 1024);
write
Writes to a file.
print $fh "Hello, World!\n";
seek
Moves the file pointer.
seek($fh, 0, 0); # Move to the beginning of the file
tell
Returns the current position of the file pointer.
my $pos = tell($fh);
print "Current Position: $pos\n";
eof
Checks if the end of the file has been reached.
if (eof($fh)) {
print "End of file reached\n";
}
5. Regular Expression Functions
m//
Matches a regular expression.
my $str = "Hello, World!";
if ($str =~ m/World/) {
print "Match found\n"; # Output: Match found
}
s///
Substitutes a regular expression.
my $str = "Hello, World!";
$str =~ s/World/Perl/;
print "Substituted String: $str\n"; # Output: Substituted String: Hello, Perl!
tr///
Translates characters.
my $str = "Hello, World!";
$str =~ tr/a-z/A-Z/;
print "Translated String: $str\n"; # Output: Translated String: HELLO, WORLD!
6. Mathematical Functions
abs
Returns the absolute value.
my $num = -42;
my $abs_num = abs($num);
print "Absolute Value: $abs_num\n"; # Output: Absolute Value: 42
sqrt
Returns the square root.
my $num = 16;
my $sqrt_num = sqrt($num);
print "Square Root: $sqrt_num\n"; # Output: Square Root: 4
int
Returns the integer part of a number.
my $num = 3.14;
my $int_num = int($num);
print "Integer Part: $int_num\n"; # Output: Integer Part: 3
rand
Returns a random number.
my $rand_num = rand(10);
print "Random Number: $rand_num\n"; # Output: Random Number: [0, 10)
srand
Seeds the random number generator.
srand(42);
my $rand_num = rand(10);
print "Seeded Random Number: $rand_num\n";
7. Time Functions
time
Returns the current time in seconds since the epoch.
my $current_time = time;
print "Current Time: $current_time\n";
localtime
Converts a time to local time.
my @local_time = localtime(time);
print "Local Time: @local_time\n";
gmtime
Converts a time to GMT.
my @gm_time = gmtime(time);
print "GMT: @gm_time\n";
sleep
Pauses the script for a specified number of seconds.
sleep(5);
print "Slept for 5 seconds\n";
8. Miscellaneous Functions
defined
Checks if a variable is defined.
my $var;
if (defined $var) {
print "Variable is defined\n";
} else {
print "Variable is not defined\n"; # Output: Variable is not defined
}
undef
Undefines a variable.
my $var = 42;
undef $var;
if (defined $var) {
print "Variable is defined\n";
} else {
print "Variable is not defined\n"; # Output: Variable is not defined
}
ref
Returns the reference type of a variable.
my $array_ref = [1, 2, 3];
my $ref_type = ref($array_ref);
print "Reference Type: $ref_type\n"; # Output: Reference Type: ARRAY
eval
Evaluates a string as Perl code.
my $code = 'print "Hello, World!\n"';
eval $code; # Output: Hello, World!
die
Exits the script with an error message.
die "Fatal error occurred\n";
warn
Prints a warning message.
warn "This is a warning\n";
exit
Exits the script.
exit;
9. List and Scalar Functions
grep
Filters elements of a list based on a condition.
my @numbers = (1, 2, 3, 4, 5);
my @even_numbers = grep { $_ % 2 == 0 } @numbers;
print "Even Numbers: @even_numbers\n"; # Output: Even Numbers: 2 4
map
Transforms elements of a list.
my @numbers = (1, 2, 3);
my @squared_numbers = map { $_ * $_ } @numbers;
print "Squared Numbers: @squared_numbers\n"; # Output: Squared Numbers: 1 4 9
scalar
Returns the number of elements in an array in scalar context.
my @array = (1, 2, 3);
my $count = scalar @array;
print "Array Count: $count\n"; # Output: Array Count: 3
reverse
(in scalar context)
Reverses a string.
my $str = "Hello, World!";
my $reversed_str = scalar reverse $str;
print "Reversed String: $reversed_str\n"; # Output: Reversed String: !dlroW ,olleH
10. Input/Output Functions
print
Prints output to standard output.
print "Hello, World!\n"; # Output: Hello, World!
printf
Formats and prints output.
my $name = "Alice";
my $age = 30;
printf "Name: %s, Age: %d\n", $name, $age; # Output: Name: Alice, Age: 30
say
Prints output with a newline (requires use feature 'say';
).
use feature 'say';
say "Hello, World!"; # Output: Hello, World! (with newline)
readline
Reads a line from a filehandle.
open(my $fh, '<', 'file.txt') or die "Cannot open file: $!";
my $line = readline($fh);
print "First Line: $line\n";
close($fh);
getc
Reads a single character from a filehandle.
open(my $fh, '<', 'file.txt') or die "Cannot open file: $!";
my $char = getc($fh);
print "First Character: $char\n";
close($fh);
11. File Test Operators
-e
Checks if a file exists.
if (-e 'file.txt') {
print "File exists\n";
} else {
print "File does not exist\n";
}
-f
Checks if a file is a plain file.
if (-f 'file.txt') {
print "It's a plain file\n";
}
-d
Checks if a file is a directory.
if (-d 'directory') {
print "It's a directory\n";
}
-r
Checks if a file is readable.
if (-r 'file.txt') {
print "File is readable\n";
}
-w
Checks if a file is writable.
if (-w 'file.txt') {
print "File is writable\n";
}
-x
Checks if a file is executable.
if (-x 'script.pl') {
print "File is executable\n";
}
-s
Returns the size of a file in bytes.
my $size = -s 'file.txt';
print "File Size: $size bytes\n";
12. System Interaction Functions
system
Executes a system command.
system("ls -l"); # Lists files in the current directory
exec
Replaces the current process with another program.
exec("ls -l"); # Replaces the Perl script with the `ls` command
backticks
(``)
Captures the output of a system command.
my $output = `ls -l`;
print "Command Output:\n$output\n";
fork
Creates a child process.
my $pid = fork;
if ($pid == 0) {
print "Child Process\n";
exit;
} else {
print "Parent Process\n";
}
wait
Waits for a child process to finish.
my $pid = fork;
if ($pid == 0) {
print "Child Process\n";
exit;
} else {
wait;
print "Parent Process: Child finished\n";
}
13. Error Handling Functions
warn
Prints a warning message to STDERR.
warn "This is a warning message\n";
die
Exits the program with an error message.
die "Fatal error occurred\n";
eval
Evaluates a block of code and catches errors.
eval {
die "An error occurred\n";
};
if ($@) {
print "Error caught: $@\n";
}
14. Reference and Data Structure Functions
ref
Returns the type of a reference.
my $array_ref = [1, 2, 3];
print "Reference Type: ", ref($array_ref), "\n"; # Output: Reference Type: ARRAY
bless
Associates an object with a class.
package MyClass;
sub new {
my $self = {};
bless $self, 'MyClass';
return $self;
}
my $obj = MyClass->new();
print "Object is blessed into: ", ref($obj), "\n"; # Output: Object is blessed into: MyClass
defined
Checks if a variable is defined.
my $var;
if (defined $var) {
print "Variable is defined\n";
} else {
print "Variable is not defined\n"; # Output: Variable is not defined
}
15. Miscellaneous Functions
caller
Returns information about the caller of a subroutine.
sub foo {
my ($package, $filename, $line) = caller;
print "Called from package: $package, file: $filename, line: $line\n";
}
foo();
require
Loads a Perl module or file.
require 'module.pl';
use
Loads a Perl module at compile time.
use strict;
use warnings;
package
Declares a package namespace.
package MyPackage;
sub hello {
print "Hello from MyPackage\n";
}
MyPackage::hello(); # Output: Hello from MyPackage
tie
Binds a variable to a class implementing TIEHASH
, TIEARRAY
, etc.
tie my %hash, 'Tie::Hash';
16. Special Variables and Functions
$_
Default variable for many functions.
foreach (1..5) {
print "$_\n"; # Output: 1 2 3 4 5
}
@_
Subroutine argument list.
sub greet {
my ($name) = @_;
print "Hello, $name!\n";
}
greet("Alice"); # Output: Hello, Alice!
$!
Error message from the last system call.
open(my $fh, '<', 'nonexistent.txt') or die "Error: $!\n";
$@
Error message from the last eval
block.
eval { die "An error occurred\n" };
print "Error: $@" if $@;
17. Advanced String Functions
quotemeta
Escapes all non-alphanumeric characters in a string.
my $str = "Hello, World! (123)";
my $escaped_str = quotemeta($str);
print "Escaped String: $escaped_str\n"; # Output: Escaped String: Hello\,\ World\!\ \(123\)
pack
Converts a list of values into a binary string.
my $binary_str = pack("C*", 65, 66, 67);
print "Binary String: $binary_str\n"; # Output: Binary String: ABC
unpack
Converts a binary string into a list of values.
my @values = unpack("C*", "ABC");
print "Values: @values\n"; # Output: Values: 65 66 67
chr
Returns the character corresponding to an ASCII value.
my $char = chr(65);
print "Character: $char\n"; # Output: Character: A
ord
Returns the ASCII value of a character.
my $ascii = ord('A');
print "ASCII Value: $ascii\n"; # Output: ASCII Value: 65
18. Advanced Array Functions
splice
(Advanced Usage)
Replaces elements in an array.
my @array = (1, 2, 3, 4, 5);
splice @array, 1, 2, (6, 7, 8);
print "Array: @array\n"; # Output: Array: 1 6 7 8 4 5
grep
(Advanced Usage)
Filters elements based on a complex condition.
my @numbers = (1, 2, 3, 4, 5);
my @filtered = grep { $_ > 2 && $_ < 5 } @numbers;
print "Filtered Numbers: @filtered\n"; # Output: Filtered Numbers: 3 4
map
(Advanced Usage)
Transforms elements based on a complex condition.
my @numbers = (1, 2, 3);
my @transformed = map { $_ * 2 } @numbers;
print "Transformed Numbers: @transformed\n"; # Output: Transformed Numbers: 2 4 6
19. Advanced Hash Functions
each
(Advanced Usage)
Iterates over key-value pairs in a hash.
my %hash = (a => 1, b => 2, c => 3);
while (my ($key, $value) = each %hash) {
print "$key => $value\n";
}
# Output:
# a => 1
# b => 2
# c => 3
keys
(Advanced Usage)
Sorts keys of a hash.
my %hash = (b => 2, a => 1, c => 3);
my @sorted_keys = sort keys %hash;
print "Sorted Keys: @sorted_keys\n"; # Output: Sorted Keys: a b c
values
(Advanced Usage)
Sorts values of a hash.
my %hash = (a => 3, b => 1, c => 2);
my @sorted_values = sort values %hash;
print "Sorted Values: @sorted_values\n"; # Output: Sorted Values: 1 2 3
20. Advanced File Handling Functions
stat
Returns file statistics.
my @stats = stat('file.txt');
print "File Size: $stats[7] bytes\n";
lstat
Returns file statistics for symbolic links.
my @stats = lstat('symlink.txt');
print "File Size: $stats[7] bytes\n";
rename
Renames a file.
rename('old.txt', 'new.txt') or die "Cannot rename file: $!";
unlink
Deletes a file.
unlink('file.txt') or die "Cannot delete file: $!";
link
Creates a hard link.
link('file.txt', 'hardlink.txt') or die "Cannot create hard link: $!";
symlink
Creates a symbolic link.
symlink('file.txt', 'symlink.txt') or die "Cannot create symlink: $!";
mkdir
Creates a directory.
mkdir('new_directory') or die "Cannot create directory: $!";
rmdir
Removes a directory.
rmdir('empty_directory') or die "Cannot remove directory: $!";
21. Advanced System Interaction Functions
alarm
Sets a timer to deliver a signal.
alarm(5);
print "Alarm set for 5 seconds\n";
kill
Sends a signal to a process.
kill('TERM', $pid);
getpgrp
Returns the process group ID.
my $pgrp = getpgrp();
print "Process Group ID: $pgrp\n";
setpgrp
Sets the process group ID.
setpgrp(0, 0);
getppid
Returns the parent process ID.
my $ppid = getppid();
print "Parent Process ID: $ppid\n";
getpriority
Returns the current priority of a process.
my $priority = getpriority(0, 0);
print "Process Priority: $priority\n";
setpriority
Sets the priority of a process.
setpriority(0, 0, 10);
22. Advanced Error Handling Functions
croak
Exits with an error message (from Carp
module).
use Carp;
croak "Fatal error occurred\n";
confess
Exits with a stack trace (from Carp
module).
use Carp;
confess "Fatal error occurred\n";
23. Advanced Regular Expression Functions
qr
Compiles a regular expression.
my $regex = qr/foo/;
if ("foo" =~ $regex) {
print "Match found\n"; # Output: Match found
}
pos
Returns or sets the position of the last match.
my $str = "foo bar foo";
$str =~ /foo/g;
print "Position: ", pos($str), "\n"; # Output: Position: 3
study
Optimizes a string for repeated pattern matching.
my $str = "Hello, World!";
study($str);
if ($str =~ /World/) {
print "Match found\n"; # Output: Match found
}
24. Advanced Mathematical Functions
atan2
Returns the arctangent of Y/X in radians.
my $angle = atan2(1, 1);
print "Angle: $angle radians\n"; # Output: Angle: 0.785398163397448 radians
exp
Returns the exponential of a number.
my $exp = exp(1);
print "Exponential: $exp\n"; # Output: Exponential: 2.71828182845905
log
Returns the natural logarithm of a number.
my $log = log(10);
print "Natural Logarithm: $log\n"; # Output: Natural Logarithm: 2.30258509299405
sin
Returns the sine of a number.
my $sin = sin(1);
print "Sine: $sin\n"; # Output: Sine: 0.841470984807897
cos
Returns the cosine of a number.
my $cos = cos(1);
print "Cosine: $cos\n"; # Output: Cosine: 0.54030230586814
rand
(Advanced Usage)
Generates a random number within a range.
my $rand_num = int(rand(100));
print "Random Number: $rand_num\n"; # Output: Random Number: [0, 99]
25. Advanced Miscellaneous Functions
tied
Returns the object underlying a tied variable.
tie my %hash, 'Tie::Hash';
my $obj = tied %hash;
print "Tied Object: $obj\n";
untie
Breaks the binding between a variable and a package.
untie %hash;
formline
Formats a string (used with format
).
formline("Hello, @<<<<", "World");
print $^A; # Output: Hello, World
vec
Treats a string as a vector of unsigned integers.
my $str = "ABC";
vec($str, 0, 8) = 88;
print "Modified String: $str\n"; # Output: Modified String: XBC
26. Advanced Input/Output Functions
select
Changes the default filehandle for output.
open(my $fh, '>', 'output.txt') or die "Cannot open file: $!";
select $fh;
print "This goes to output.txt\n";
select STDOUT; # Switch back to STDOUT
print "This goes to the screen\n";
close($fh);
sysread
Reads a fixed number of bytes from a filehandle.
open(my $fh, '<', 'file.txt') or die "Cannot open file: $!";
my $buffer;
sysread($fh, $buffer, 1024);
print "Read Data: $buffer\n";
close($fh);
syswrite
Writes a fixed number of bytes to a filehandle.
open(my $fh, '>', 'output.txt') or die "Cannot open file: $!";
syswrite($fh, "Hello, World!", 13);
close($fh);
fcntl
Performs low-level file control operations.
use Fcntl;
fcntl($fh, F_SETFL, O_NONBLOCK);
ioctl
Performs device-specific input/output operations.
use IO::Handle;
ioctl($fh, 0x1234, $arg);
27. Advanced System Interaction Functions
pipe
Creates a pair of filehandles for interprocess communication.
pipe(my $reader, my $writer);
print $writer "Hello, World!\n";
close($writer);
my $message = <$reader>;
print "Message: $message\n"; # Output: Message: Hello, World!
close($reader);
socket
Creates a socket for network communication.
use Socket;
socket(my $sock, PF_INET, SOCK_STREAM, getprotobyname('tcp'));
bind
Binds a socket to an address.
my $port = 12345;
my $addr = sockaddr_in($port, INADDR_ANY);
bind($sock, $addr) or die "Cannot bind socket: $!";
listen
Listens for incoming connections on a socket.
listen($sock, 5) or die "Cannot listen on socket: $!";
accept
Accepts an incoming connection on a socket.
my $client_addr = accept(my $client_sock, $sock);
print "Connection accepted\n";
shutdown
Shuts down a socket.
shutdown($sock, 2); # 2 means shut down both reading and writing
28. Advanced Error Handling Functions
carp
Prints a warning message with a stack trace (from Carp
module).
use Carp;
carp "This is a warning message\n";
cluck
Prints a warning message with a full stack trace (from Carp
module).
use Carp;
cluck "This is a warning message\n";
eval
(Advanced Usage)
Evaluates a block of code and catches errors.
eval {
die "An error occurred\n";
};
if ($@) {
print "Error caught: $@\n";
}
29. Advanced Regular Expression Functions
qr
(Advanced Usage)
Compiles a regular expression with modifiers.
my $regex = qr/foo/i; # Case-insensitive match
if ("FOO" =~ $regex) {
print "Match found\n"; # Output: Match found
}
pos
(Advanced Usage)
Sets the position of the last match.
my $str = "foo bar foo";
$str =~ /foo/g;
pos($str) = 4;
if ($str =~ /foo/g) {
print "Match found at position ", pos($str), "\n"; # Output: Match found at position 8
}
study
(Advanced Usage)
Optimizes a string for repeated pattern matching.
my $str = "Hello, World!";
study($str);
if ($str =~ /World/) {
print "Match found\n"; # Output: Match found
}
30. Advanced Mathematical Functions
atan2
(Advanced Usage)
Returns the arctangent of Y/X in radians.
my $angle = atan2(1, 1);
print "Angle: $angle radians\n"; # Output: Angle: 0.785398163397448 radians
exp
(Advanced Usage)
Returns the exponential of a number.
my $exp = exp(1);
print "Exponential: $exp\n"; # Output: Exponential: 2.71828182845905
log
(Advanced Usage)
Returns the natural logarithm of a number.
my $log = log(10);
print "Natural Logarithm: $log\n"; # Output: Natural Logarithm: 2.30258509299405
sin
(Advanced Usage)
Returns the sine of a number.
my $sin = sin(1);
print "Sine: $sin\n"; # Output: Sine: 0.841470984807897
cos
(Advanced Usage)
Returns the cosine of a number.
my $cos = cos(1);
print "Cosine: $cos\n"; # Output: Cosine: 0.54030230586814
rand
(Advanced Usage)
Generates a random number within a range.
my $rand_num = int(rand(100));
print "Random Number: $rand_num\n"; # Output: Random Number: [0, 99]
31. Advanced Miscellaneous Functions
tied
(Advanced Usage)
Returns the object underlying a tied variable.
tie my %hash, 'Tie::Hash';
my $obj = tied %hash;
print "Tied Object: $obj\n";
untie
(Advanced Usage)
Breaks the binding between a variable and a package.
untie %hash;
formline
(Advanced Usage)
Formats a string (used with format
).
formline("Hello, @<<<<", "World");
print $^A; # Output: Hello, World
vec
(Advanced Usage)
Treats a string as a vector of unsigned integers.
my $str = "ABC";
vec($str, 0, 8) = 88;
print "Modified String: $str\n"; # Output: Modified String: XBC
32. Advanced Special Variables
$^O
Returns the operating system name.
print "Operating System: $^O\n"; # Output: Operating System: linux (or darwin, MSWin32, etc.)
$^T
Returns the time the script started running.
print "Script Start Time: $^T\n"; # Output: Script Start Time: [epoch time]
$^X
Returns the name of the Perl executable.
print "Perl Executable: $^X\n"; # Output: Perl Executable: /usr/bin/perl
$^V
Returns the Perl version.
print "Perl Version: $^V\n"; # Output: Perl Version: v5.34.0 (or similar)
$^W
Returns the current value of the warning flag.
print "Warning Flag: $^W\n"; # Output: Warning Flag: 1 (if warnings are enabled)
33. Advanced File Test Operators
-M
Returns the age of the file in days since the script started.
my $age = -M 'file.txt';
print "File Age: $age days\n";
-C
Returns the inode change age of the file in days.
my $inode_age = -C 'file.txt';
print "Inode Change Age: $inode_age days\n";
-A
Returns the access age of the file in days.
my $access_age = -A 'file.txt';
print "Access Age: $access_age days\n";
34. Advanced Input/Output Functions
sysseek
Moves the file pointer to a specific position.
open(my $fh, '+<', 'file.txt') or die "Cannot open file: $!";
sysseek($fh, 10, 0); # Move to the 10th byte
print $fh "Hello";
close($fh);
truncate
Truncates a file to a specified length.
open(my $fh, '+<', 'file.txt') or die "Cannot open file: $!";
truncate($fh, 100); # Truncate file to 100 bytes
close($fh);
flock
Locks a file for exclusive access.
open(my $fh, '>>', 'file.txt') or die "Cannot open file: $!";
flock($fh, 2) or die "Cannot lock file: $!"; # 2 means exclusive lock
print $fh "Exclusive access\n";
flock($fh, 8); # 8 means unlock
close($fh);
fcntl
(Advanced Usage)
Performs low-level file control operations.
use Fcntl;
fcntl($fh, F_SETFL, O_NONBLOCK);
ioctl
(Advanced Usage)
Performs device-specific input/output operations.
use IO::Handle;
ioctl($fh, 0x1234, $arg);
35. Advanced System Interaction Functions
pipe
(Advanced Usage)
Creates a pair of filehandles for interprocess communication.
pipe(my $reader, my $writer);
print $writer "Hello, World!\n";
close($writer);
my $message = <$reader>;
print "Message: $message\n"; # Output: Message: Hello, World!
close($reader);
socket
(Advanced Usage)
Creates a socket for network communication.
use Socket;
socket(my $sock, PF_INET, SOCK_STREAM, getprotobyname('tcp'));
bind
(Advanced Usage)
Binds a socket to an address.
my $port = 12345;
my $addr = sockaddr_in($port, INADDR_ANY);
bind($sock, $addr) or die "Cannot bind socket: $!";
listen
(Advanced Usage)
Listens for incoming connections on a socket.
listen($sock, 5) or die "Cannot listen on socket: $!";
accept
(Advanced Usage)
Accepts an incoming connection on a socket.
my $client_addr = accept(my $client_sock, $sock);
print "Connection accepted\n";
shutdown
(Advanced Usage)
Shuts down a socket.
shutdown($sock, 2); # 2 means shut down both reading and writing
36. Advanced Error Handling Functions
carp
(Advanced Usage)
Prints a warning message with a stack trace (from Carp
module).
use Carp;
carp "This is a warning message\n";
cluck
(Advanced Usage)
Prints a warning message with a full stack trace (from Carp
module).
use Carp;
cluck "This is a warning message\n";
eval
(Advanced Usage)
Evaluates a block of code and catches errors.
eval {
die "An error occurred\n";
};
if ($@) {
print "Error caught: $@\n";
}
37. Advanced Regular Expression Functions
qr
(Advanced Usage)
Compiles a regular expression with modifiers.
my $regex = qr/foo/i; # Case-insensitive match
if ("FOO" =~ $regex) {
print "Match found\n"; # Output: Match found
}
pos
(Advanced Usage)
Sets the position of the last match.
my $str = "foo bar foo";
$str =~ /foo/g;
pos($str) = 4;
if ($str =~ /foo/g) {
print "Match found at position ", pos($str), "\n"; # Output: Match found at position 8
}
study
(Advanced Usage)
Optimizes a string for repeated pattern matching.
my $str = "Hello, World!";
study($str);
if ($str =~ /World/) {
print "Match found\n"; # Output: Match found
}
38. Advanced Mathematical Functions
atan2
(Advanced Usage)
Returns the arctangent of Y/X in radians.
my $angle = atan2(1, 1);
print "Angle: $angle radians\n"; # Output: Angle: 0.785398163397448 radians
exp
(Advanced Usage)
Returns the exponential of a number.
my $exp = exp(1);
print "Exponential: $exp\n"; # Output: Exponential: 2.71828182845905
log
(Advanced Usage)
Returns the natural logarithm of a number.
my $log = log(10);
print "Natural Logarithm: $log\n"; # Output: Natural Logarithm: 2.30258509299405
sin
(Advanced Usage)
Returns the sine of a number.
my $sin = sin(1);
print "Sine: $sin\n"; # Output: Sine: 0.841470984807897
cos
(Advanced Usage)
Returns the cosine of a number.
my $cos = cos(1);
print "Cosine: $cos\n"; # Output: Cosine: 0.54030230586814
rand
(Advanced Usage)
Generates a random number within a range.
my $rand_num = int(rand(100));
print "Random Number: $rand_num\n"; # Output: Random Number: [0, 99]
39. Advanced Miscellaneous Functions
tied
(Advanced Usage)
Returns the object underlying a tied variable.
tie my %hash, 'Tie::Hash';
my $obj = tied %hash;
print "Tied Object: $obj\n";
untie
(Advanced Usage)
Breaks the binding between a variable and a package.
untie %hash;
formline
(Advanced Usage)
Formats a string (used with format
).
formline("Hello, @<<<<", "World");
print $^A; # Output: Hello, World
vec
(Advanced Usage)
Treats a string as a vector of unsigned integers.
my $str = "ABC";
vec($str, 0, 8) = 88;
print "Modified String: $str\n"; # Output: Modified String: XBC
40. Advanced Special Variables
$^O
Returns the operating system name.
print "Operating System: $^O\n"; # Output: Operating System: linux (or darwin, MSWin32, etc.)
$^T
Returns the time the script started running.
print "Script Start Time: $^T\n"; # Output: Script Start Time: [epoch time]
$^X
Returns the name of the Perl executable.
print "Perl Executable: $^X\n"; # Output: Perl Executable: /usr/bin/perl
$^V
Returns the Perl version.
print "Perl Version: $^V\n"; # Output: Perl Version: v5.34.0 (or similar)
$^W
Returns the current value of the warning flag.
print "Warning Flag: $^W\n"; # Output: Warning Flag: 1 (if warnings are enabled)
41. Advanced File Test Operators
-M
Returns the age of the file in days since the script started.
my $age = -M 'file.txt';
print "File Age: $age days\n";
-C
Returns the inode change age of the file in days.
my $inode_age = -C 'file.txt';
print "Inode Change Age: $inode_age days\n";
-A
Returns the access age of the file in days.
my $access_age = -A 'file.txt';
print "Access Age: $access_age days\n";
42. Advanced File and Directory Functions
opendir
Opens a directory for reading.
opendir(my $dh, 'directory') or die "Cannot open directory: $!";
while (my $file = readdir($dh)) {
print "File: $file\n";
}
closedir($dh);
readdir
Reads entries from a directory handle.
opendir(my $dh, 'directory') or die "Cannot open directory: $!";
my @files = readdir($dh);
closedir($dh);
print "Files: @files\n";
rewinddir
Resets the position of a directory handle to the beginning.
opendir(my $dh, 'directory') or die "Cannot open directory: $!";
readdir($dh); # Read some entries
rewinddir($dh); # Reset to the beginning
closedir($dh);
telldir
Returns the current position of a directory handle.
opendir(my $dh, 'directory') or die "Cannot open directory: $!";
readdir($dh);
my $pos = telldir($dh);
print "Directory Position: $pos\n";
closedir($dh);
seekdir
Sets the position of a directory handle.
opendir(my $dh, 'directory') or die "Cannot open directory: $!";
seekdir($dh, 0); # Reset to the beginning
closedir($dh);
mkdir
(Advanced Usage)
Creates a directory with specific permissions.
mkdir('new_directory', 0755) or die "Cannot create directory: $!";
rmdir
(Advanced Usage)
Removes an empty directory.
rmdir('empty_directory') or die "Cannot remove directory: $!";
43. Advanced Process Control Functions
waitpid
Waits for a specific child process to finish.
my $pid = fork;
if ($pid == 0) {
print "Child Process\n";
exit;
} else {
waitpid($pid, 0);
print "Parent Process: Child finished\n";
}
getpwnam
Gets user information by name.
my $user_info = getpwnam('root');
print "User Info: $user_info\n";
getgrnam
Gets group information by name.
my $group_info = getgrnam('wheel');
print "Group Info: $group_info\n";
getpwuid
Gets user information by UID.
my $user_info = getpwuid(0);
print "User Info: $user_info\n";
getgrgid
Gets group information by GID.
my $group_info = getgrgid(0);
print "Group Info: $group_info\n";
44. Advanced Signal Handling Functions
%SIG
Handles signals in Perl.
$SIG{INT} = sub { print "Caught SIGINT\n"; exit; };
print "Press Ctrl+C to trigger SIGINT\n";
sleep(10);
kill
(Advanced Usage)
Sends a signal to a process.
kill('TERM', $pid);
alarm
(Advanced Usage)
Sets a timer to deliver a signal.
alarm
45. Advanced Networking Functions
gethostbyname
Gets host information by name.
my $host_info = gethostbyname('localhost');
print "Host Info: $host_info\n";
gethostbyaddr
Gets host information by address.
my $addr = inet_aton('127.0.0.1');
my $host_info = gethostbyaddr($addr, AF_INET);
print "Host Info: $host_info\n";
getservbyname
Gets service information by name.
my $service_info = getservbyname('http', 'tcp');
print "Service Info: $service_info\n";
getservbyport
Gets service information by port.
my $service_info = getservbyport(80, 'tcp');
print "Service Info: $service_info\n";
46. Advanced Data Manipulation Functions
pack
(Advanced Usage)
Converts a list of values into a binary string.
my $binary_str = pack("C*", 65, 66, 67);
print "Binary String: $binary_str\n"; # Output: Binary String: ABC
unpack
(Advanced Usage)
Converts a binary string into a list of values.
my @values = unpack("C*", "ABC");
print "Values: @values\n"; # Output: Values: 65 66 67
vec
(Advanced Usage)
Treats a string as a vector of unsigned integers.
my $str = "ABC";
vec($str, 0, 8) = 88;
print "Modified String: $str\n"; # Output: Modified String: XBC
47. Advanced Object-Oriented Programming Functions
bless
(Advanced Usage)
Associates an object with a class.
package MyClass;
sub new {
my $self = {};
bless $self, 'MyClass';
return $self;
}
my $obj = MyClass->new();
print "Object is blessed into: ", ref($obj), "\n"; # Output: Object is blessed into: MyClass
ref
(Advanced Usage)
Returns the type of a reference.
my $array_ref = [1, 2, 3];
print "Reference Type: ", ref($array_ref), "\n"; # Output: Reference Type: ARRAY
tie
(Advanced Usage)
Binds a variable to a class implementing TIEHASH
, TIEARRAY
, etc.
tie my %hash, 'Tie::Hash';
untie
(Advanced Usage)
Breaks the binding between a variable and a package.
untie %hash;
48. Advanced Miscellaneous Functions
caller
(Advanced Usage)
Returns information about the caller of a subroutine.
sub foo {
my ($package, $filename, $line) = caller;
print "Called from package: $package, file: $filename, line: $line\n";
}
foo();
require
(Advanced Usage)
Loads a Perl module or file.
require 'module.pl';
use
(Advanced Usage)
Loads a Perl module at compile time.
use strict;
use warnings;
package
(Advanced Usage)
Declares a package namespace.
package MyPackage;
sub hello {
print "Hello from MyPackage\n";
}
MyPackage::hello(); # Output: Hello from MyPackage
49. Advanced Special Variables
$^O
Returns the operating system name.
print "Operating System: $^O\n"; # Output: Operating System: linux (or darwin, MSWin32, etc.)
$^T
Returns the time the script started running.
print "Script Start Time: $^T\n"; # Output: Script Start Time: [epoch time]
$^X
Returns the name of the Perl executable.
print "Perl Executable: $^X\n"; # Output: Perl Executable: /usr/bin/perl
$^V
Returns the Perl version.
print "Perl Version: $^V\n"; # Output: Perl Version: v5.34.0 (or similar)
$^W
Returns the current value of the warning flag.
print "Warning Flag: $^W\n"; # Output: Warning Flag: 1 (if warnings are enabled)
50. Advanced File Test Operators
-M
Returns the age of the file in days since the script started.
my $age = -M 'file.txt';
print "File Age: $age days\n";
-C
Returns the inode change age of the file in days.
my $inode_age = -C 'file.txt';
print "Inode Change Age: $inode_age days\n";
-A
Returns the access age of the file in days.
my $access_age = -A 'file.txt';
print "Access Age: $access_age days\n";
51. Advanced Input/Output Functions
sysread
Reads a fixed number of bytes from a filehandle.
open(my $fh, '<', 'file.txt') or die "Cannot open file: $!";
my $buffer;
sysread($fh, $buffer, 1024);
print "Read Data: $buffer\n";
close($fh);
syswrite
Writes a fixed number of bytes to a filehandle.
open(my $fh, '>', 'output.txt') or die "Cannot open file: $!";
syswrite($fh, "Hello, World!", 13);
close($fh);
fcntl
Performs low-level file control operations.
use Fcntl;
fcntl($fh, F_SETFL, O_NONBLOCK);
ioctl
Performs device-specific input/output operations.
use IO::Handle;
ioctl($fh, 0x1234, $arg);
52. Advanced System Interaction Functions
pipe
Creates a pair of filehandles for interprocess communication.
pipe(my $reader, my $writer);
print $writer "Hello, World!\n";
close($writer);
my $message = <$reader>;
print "Message: $message\n"; # Output: Message: Hello, World!
close($reader);
socket
Creates a socket for network communication.
use Socket;
socket(my $sock, PF_INET, SOCK_STREAM, getprotobyname('tcp'));
bind
Binds a socket to an address.
my $port = 12345;
my $addr = sockaddr_in($port, INADDR_ANY);
bind($sock, $addr) or die "Cannot bind socket: $!";
listen
Listens for incoming connections on a socket.
listen($sock, 5) or die "Cannot listen on socket: $!";
accept
Accepts an incoming connection on a socket.
my $client_addr = accept(my $client_sock, $sock);
print "Connection accepted\n";
shutdown
Shuts down a socket.
shutdown($sock, 2); # 2 means shut down both reading and writing
53. Advanced Error Handling Functions
carp
Prints a warning message with a stack trace (from Carp
module).
use Carp;
carp "This is a warning message\n";
cluck
Prints a warning message with a full stack trace (from Carp
module).
use Carp;
cluck "This is a warning message\n";
eval
(Advanced Usage)
Evaluates a block of code and catches errors.
eval {
die "An error occurred\n";
};
if ($@) {
print "Error caught: $@\n";
}
54. Advanced Regular Expression Functions
qr
(Advanced Usage)
Compiles a regular expression with modifiers.
my $regex = qr/foo/i; # Case-insensitive match
if ("FOO" =~ $regex) {
print "Match found\n"; # Output: Match found
}
pos
(Advanced Usage)
Sets the position of the last match.
my $str = "foo bar foo";
$str =~ /foo/g;
pos($str) = 4;
if ($str =~ /foo/g) {
print "Match found at position ", pos($str), "\n"; # Output: Match found at position 8
}
study
(Advanced Usage)
Optimizes a string for repeated pattern matching.
my $str = "Hello, World!";
study($str);
if ($str =~ /World/) {
print "Match found\n"; # Output: Match found
}
55. Advanced Mathematical Functions
atan2
(Advanced Usage)
Returns the arctangent of Y/X in radians.
my $angle = atan2(1, 1);
print "Angle: $angle radians\n"; # Output: Angle: 0.785398163397448 radians
exp
(Advanced Usage)
Returns the exponential of a number.
my $exp = exp(1);
print "Exponential: $exp\n"; # Output: Exponential: 2.71828182845905
log
(Advanced Usage)
Returns the natural logarithm of a number.
my $log = log(10);
print "Natural Logarithm: $log\n"; # Output: Natural Logarithm: 2.30258509299405
sin
(Advanced Usage)
Returns the sine of a number.
my $sin = sin(1);
print "Sine: $sin\n"; # Output: Sine: 0.841470984807897
cos
(Advanced Usage)
Returns the cosine of a number.
my $cos = cos(1);
print "Cosine: $cos\n"; # Output: Cosine: 0.54030230586814
rand
(Advanced Usage)
Generates a random number within a range.
my $rand_num = int(rand(100));
print "Random Number: $rand_num\n"; # Output: Random Number: [0, 99]
56. Advanced Miscellaneous Functions
tied
(Advanced Usage)
Returns the object underlying a tied variable.
tie my %hash, 'Tie::Hash';
my $obj = tied %hash;
print "Tied Object: $obj\n";
untie
(Advanced Usage)
Breaks the binding between a variable and a package.
untie %hash;
formline
(Advanced Usage)
Formats a string (used with format
).
formline("Hello, @<<<<", "World");
print $^A; # Output: Hello, World
vec
(Advanced Usage)
Treats a string as a vector of unsigned integers.
my $str = "ABC";
vec($str, 0, 8) = 88;
print "Modified String: $str\n"; # Output: Modified String: XBC
57. Advanced Special Variables
$^O
Returns the operating system name.
print "Operating System: $^O\n"; # Output: Operating System: linux (or darwin, MSWin32, etc.)
$^T
Returns the time the script started running.
print "Script Start Time: $^T\n"; # Output: Script Start Time: [epoch time]
$^X
Returns the name of the Perl executable.
print "Perl Executable: $^X\n"; # Output: Perl Executable: /usr/bin/perl
$^V
Returns the Perl version.
print "Perl Version: $^V\n"; # Output: Perl Version: v5.34.0 (or similar)
$^W
Returns the current value of the warning flag.
print "Warning Flag: $^W\n"; # Output: Warning Flag: 1 (if warnings are enabled)
58. Advanced File Test Operators
-M
Returns the age of the file in days since the script started.
my $age = -M 'file.txt';
print "File Age: $age days\n";
-C
Returns the inode change age of the file in days.
my $inode_age = -C 'file.txt';
print "Inode Change Age: $inode_age days\n";
-A
Returns the access age of the file in days.
my $access_age = -A 'file.txt';
print "Access Age: $access_age days\n";
59. Advanced Regular Expression Functions
study
(Advanced Usage)
Optimizes a string for repeated pattern matching.
my $str = "Hello, World!";
study($str);
if ($str =~ /World/) {
print "Match found\n"; # Output: Match found
}
pos
(Advanced Usage)
Sets the position of the last match.
my $str = "foo bar foo";
$str =~ /foo/g;
pos($str) = 4;
if ($str =~ /foo/g) {
print "Match found at position ", pos($str), "\n"; # Output: Match found at position 8
}
qr
(Advanced Usage)
Compiles a regular expression with modifiers.
my $regex = qr/foo/i; # Case-insensitive match
if ("FOO" =~ $regex) {
print "Match found\n"; # Output: Match found
}
60. Advanced Mathematical Functions
atan2
(Advanced Usage)
Returns the arctangent of Y/X in radians.
my $angle = atan2(1, 1);
print "Angle: $angle radians\n"; # Output: Angle: 0.785398163397448 radians
exp
(Advanced Usage)
Returns the exponential of a number.
my $exp = exp(1);
print "Exponential: $exp\n"; # Output: Exponential: 2.71828182845905
log
(Advanced Usage)
Returns the natural logarithm of a number.
my $log = log(10);
print "Natural Logarithm: $log\n"; # Output: Natural Logarithm: 2.30258509299405
sin
(Advanced Usage)
Returns the sine of a number.
my $sin = sin(1);
print "Sine: $sin\n"; # Output: Sine: 0.841470984807897
cos
(Advanced Usage)
Returns the cosine of a number.
my $cos = cos(1);
print "Cosine: $cos\n"; # Output: Cosine: 0.54030230586814
rand
(Advanced Usage)
Generates a random number within a range.
my $rand_num = int(rand(100));
print "Random Number: $rand_num\n"; # Output: Random Number: [0, 99]
61. Advanced Miscellaneous Functions
tied
(Advanced Usage)
Returns the object underlying a tied variable.
tie my %hash, 'Tie::Hash';
my $obj = tied %hash;
print "Tied Object: $obj\n";
untie
(Advanced Usage)
Breaks the binding between a variable and a package.
untie %hash;
formline
(Advanced Usage)
Formats a string (used with format
).
formline("Hello, @<<<<", "World");
print $^A; # Output: Hello, World
vec
(Advanced Usage)
Treats a string as a vector of unsigned integers.
my $str = "ABC";
vec($str, 0, 8) = 88;
print "Modified String: $str\n"; # Output: Modified String: XBC
62. Advanced Special Variables
$^O
Returns the operating system name.
print "Operating System: $^O\n"; # Output: Operating System: linux (or darwin, MSWin32, etc.)
$^T
Returns the time the script started running.
print "Script Start Time: $^T\n"; # Output: Script Start Time: [epoch time]
$^X
Returns the name of the Perl executable.
print "Perl Executable: $^X\n"; # Output: Perl Executable: /usr/bin/perl
$^V
Returns the Perl version.
print "Perl Version: $^V\n"; # Output: Perl Version: v5.34.0 (or similar)
$^W
Returns the current value of the warning flag.
print "Warning Flag: $^W\n"; # Output: Warning Flag: 1 (if warnings are enabled)
63. Advanced File Test Operators
-M
Returns the age of the file in days since the script started.
my $age = -M 'file.txt';
print "File Age: $age days\n";
-C
Returns the inode change age of the file in days.
my $inode_age = -C 'file.txt';
print "Inode Change Age: $inode_age days\n";
-A
Returns the access age of the file in days.
my $access_age = -A 'file.txt';
print "Access Age: $access_age days\n";
64. Advanced Input/Output Functions
sysread
Reads a fixed number of bytes from a filehandle.
open(my $fh, '<', 'file.txt') or die "Cannot open file: $!";
my $buffer;
sysread($fh, $buffer, 1024);
print "Read Data: $buffer\n";
close($fh);
syswrite
Writes a fixed number of bytes to a filehandle.
open(my $fh, '>', 'output.txt') or die "Cannot open file: $!";
syswrite($fh, "Hello, World!", 13);
close($fh);
fcntl
Performs low-level file control operations.
use Fcntl;
fcntl($fh, F_SETFL, O_NONBLOCK);
ioctl
Performs device-specific input/output operations.
use IO::Handle;
ioctl($fh, 0x1234, $arg);
65. Advanced System Interaction Functions
pipe
Creates a pair of filehandles for interprocess communication.
pipe(my $reader, my $writer);
print $writer "Hello, World!\n";
close($writer);
my $message = <$reader>;
print "Message: $message\n"; # Output: Message: Hello, World!
close($reader);
socket
Creates a socket for network communication.
use Socket;
socket(my $sock, PF_INET, SOCK_STREAM, getprotobyname('tcp'));
bind
Binds a socket to an address.
my $port = 12345;
my $addr = sockaddr_in($port, INADDR_ANY);
bind($sock, $addr) or die "Cannot bind socket: $!";
listen
Listens for incoming connections on a socket.
listen($sock, 5) or die "Cannot listen on socket: $!";
accept
Accepts an incoming connection on a socket.
my $client_addr = accept(my $client_sock, $sock);
print "Connection accepted\n";
shutdown
Shuts down a socket.
shutdown($sock, 2); # 2 means shut down both reading and writing
66. Advanced Error Handling Functions
carp
Prints a warning message with a stack trace (from Carp
module).
use Carp;
carp "This is a warning message\n";
cluck
Prints a warning message with a full stack trace (from Carp
module).
use Carp;
cluck "This is a warning message\n";
eval
(Advanced Usage)
Evaluates a block of code and catches errors.
eval {
die "An error occurred\n";
};
if ($@) {
print "Error caught: $@\n";
}
67. Advanced Regular Expression Functions
qr
(Advanced Usage)
Compiles a regular expression with modifiers.
my $regex = qr/foo/i; # Case-insensitive match
if ("FOO" =~ $regex) {
print "Match found\n"; # Output: Match found
}
pos
(Advanced Usage)
Sets the position of the last match.
my $str = "foo bar foo";
$str =~ /foo/g;
pos($str) = 4;
if ($str =~ /foo/g) {
print "Match found at position ", pos($str), "\n"; # Output: Match found at position 8
}
study
(Advanced Usage)
Optimizes a string for repeated pattern matching.
my $str = "Hello, World!";
study($str);
if ($str =~ /World/) {
print "Match found\n"; # Output: Match found
}
68. Advanced Mathematical Functions
atan2
(Advanced Usage)
Returns the arctangent of Y/X in radians.
my $angle = atan2(1, 1);
print "Angle: $angle radians\n"; # Output: Angle: 0.785398163397448 radians
exp
(Advanced Usage)
Returns the exponential of a number.
my $exp = exp(1);
print "Exponential: $exp\n"; # Output: Exponential: 2.71828182845905
log
(Advanced Usage)
Returns the natural logarithm of a number.
my $log = log(10);
print "Natural Logarithm: $log\n"; # Output: Natural Logarithm: 2.30258509299405
sin
(Advanced Usage)
Returns the sine of a number.
my $sin = sin(1);
print "Sine: $sin\n"; # Output: Sine: 0.841470984807897
cos
(Advanced Usage)
Returns the cosine of a number.
my $cos = cos(1);
print "Cosine: $cos\n"; # Output: Cosine: 0.54030230586814
rand
(Advanced Usage)
Generates a random number within a range.
my $rand_num = int(rand(100));
print "Random Number: $rand_num\n"; # Output: Random Number: [0, 99]
69. Advanced Miscellaneous Functions
tied
(Advanced Usage)
Returns the object underlying a tied variable.
tie my %hash, 'Tie::Hash';
my $obj = tied %hash;
print "Tied Object: $obj\n";
untie
(Advanced Usage)
Breaks the binding between a variable and a package.
untie %hash;
formline
(Advanced Usage)
Formats a string (used with format
).
formline("Hello, @<<<<", "World");
print $^A; # Output: Hello, World
vec
(Advanced Usage)
Treats a string as a vector of unsigned integers.
my $str = "ABC";
vec($str, 0, 8) = 88;
print "Modified String: $str\n"; # Output: Modified String: XBC
70. Advanced Special Variables
$^O
Returns the operating system name.
print "Operating System: $^O\n"; # Output: Operating System: linux (or darwin, MSWin32, etc.)
$^T
Returns the time the script started running.
print "Script Start Time: $^T\n"; # Output: Script Start Time: [epoch time]
$^X
Returns the name of the Perl executable.
print "Perl Executable: $^X\n"; # Output: Perl Executable: /usr/bin/perl
$^V
Returns the Perl version.
print "Perl Version: $^V\n"; # Output: Perl Version: v5.34.0 (or similar)
$^W
Returns the current value of the warning flag.
print "Warning Flag: $^W\n"; # Output: Warning Flag: 1 (if warnings are enabled)
71. Advanced File Test Operators
-M
Returns the age of the file in days since the script started.
my $age = -M 'file.txt';
print "File Age: $age days\n";
-C
Returns the inode change age of the file in days.
my $inode_age = -C 'file.txt';
print "Inode Change Age: $inode_age days\n";
-A
Returns the access age of the file in days.
my $access_age = -A 'file.txt';
print "Access Age: $access_age days\n";
Labels: Perl Built-ins Quick Reference
0 Comments:
Post a Comment
Note: only a member of this blog may post a comment.
<< Home