DEV Community

vinodk89
vinodk89

Posted on

Perl Weekly Challenge - 360: Perl Power: Two Tiny Scripts, Big Learning!

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)
Enter fullscreen mode Exit fullscreen mode

Output:

*Hi**
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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!"
Enter fullscreen mode Exit fullscreen mode

Output:

2 3 and apples bananas! have I
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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)