ℹ️ Select 'Choose Exercise', or randomize 'Next Random Exercise' in selected language.

Choose Exercise:
Timer 00:00
WPM --
Score --
Acc --
Correct chars --

Perl Simple String Reverser

Perl

Goal -- WPM

Ready
Exercise Algorithm Area
1sub reverse_string {
2my ($input_string) = @_;
3
4# Handle empty string edge case
5if (!defined $input_string || $input_string eq '') {
6return "";
7}
8
9# Use Perl's built-in reverse function for strings
10my $reversed_string = reverse($input_string);
11
12return $reversed_string;
13}
14
15# Helper function to demonstrate usage
16sub demonstrate_reversal {
17my ($test_string) = @_;
18my $reversed = reverse_string($test_string);
19print "Original: '$test_string' -> Reversed: '$reversed'\n";
20}
21
22# Example Usage:
23# demonstrate_reversal("hello");
24# demonstrate_reversal("A man, a plan, a canal: Panama");
25# demonstrate_reversal("");
26# demonstrate_reversal(undef);
Algorithm description viewbox

Perl Simple String Reverser

Algorithm description:

This Perl script defines a function `reverse_string` that takes a string as input and returns its reversed version. It handles the edge case of an empty or undefined input string by returning an empty string. The core logic utilizes Perl's built-in `reverse` function, which efficiently reverses strings. A helper function `demonstrate_reversal` is included to show how to use the main function with various test cases. This is a fundamental text processing task often used in introductory programming exercises.

Algorithm explanation:

The `reverse_string` function in Perl is straightforward. It first checks for an undefined or empty input string, returning an empty string immediately if either condition is met. This handles edge cases gracefully. If the input is valid, it uses Perl's highly optimized built-in `reverse` function, which operates on strings by reversing the order of characters. The time complexity of reversing a string of length N using Perl's built-in function is generally considered O(N), as each character must be visited and repositioned. The space complexity is O(N) because a new string of the same length is created to store the reversed result. The correctness relies on the well-tested nature of Perl's core functions.

Pseudocode:

Function reverse_string(input_string):
  If input_string is null or empty:
    Return empty string.
  Else:
    Return input_string reversed.

Function demonstrate_reversal(test_string):
  reversed_string = reverse_string(test_string).
  Print "Original: '" + test_string + "' -> Reversed: '" + reversed_string + "'\n".