This week, I challenged myself to write small but meaningful Perl programs for Weekly Challenge — focusing on clean logic, edge cases, and test-driven validation.
Sometimes, the simplest problems teach the strongest lessons.
Challenge 1: Text Justifier (Centering Text with Custom Padding)
Problem Statement
Write a script to return the string that centers the text within that width using asterisks * as padding.
If the string length is greater than or equal to the width, return the string as-is.
Example
Input:
("Hi", 5)
Output:
*Hi**
Implementation Highlights
- Calculated total padding required.
- Split padding evenly left and right.
- Handled odd padding differences correctly.
- Covered edge cases like:
- Empty string
- Width equal to string length
- Width smaller than string length
Key Logic
my $pad_total = $width - $len;
my $left_pad = int($pad_total / 2);
my $right_pad = $pad_total - $left_pad;
This ensures perfect centering even when padding is odd.
What I Learned
- Importance of integer division in layout formatting
- Handling edge cases makes logic robust
- Writing test cases increases confidence immediately
Challenge 2: Word Sorter (Alphabetical Word Sorting)
Problem Statement
Write a script to order words in the given sentence alphabetically but keeps the words themselves unchanged.
Example
Input:
"I have 2 apples and 3 bananas!"
Output:
2 3 and apples bananas! have I
Implementation Highlights
- Split words using whitespace regex
- Used Perl’s built-in sort
- Rejoined words with single spaces
- Managed multiple spaces correctly
Core Logic
my @words = split /\s+/, $str;
return join ' ', sort @words;
Simple. Elegant. Effective.
What I Learned
- Perl’s sort is powerful and concise
- Regex-based splitting handles messy input cleanly
- Even small scripts benefit from structured testing
Top comments (0)