Peter’s blog ✴ Week 180 ✴ 29 August 2022

THE WEEKLY CHALLENGE
Uniquely trimmed

The Perl Camel

Task 2

Trim list

You are given list of numbers, @n and an integer $i. Write a script to trim the given list where element is less than or equal to the given integer.

Examples


Example 1
Input: @n = (1,4,2,3,5) and $i = 3
Output: (4,5)

Example 2
Input: @n = (9,0,6,2,3,8,5) and $i = 4
Output: (9,6,8,5)

Analysis

Well, that was easy. This:

grep { $_ > $i } @n
gives the required answer

I am sorry that the 'Try it' feature is currently working very slowly or not at all owing to some issue with my web hosting provider.

Try it 

Try running the script with any input:



example: 9,0,6,2,3,8,5



example: 4

Script


#!/usr/bin/perl

# Blog: http://ccgi.campbellsmiths.force9.co.uk/challenge

use v5.26;    # The Weekly Challenge - 2022-08-29
use utf8;     # Week 180 - task 2 - Trim list
use warnings; # Peter Campbell Smith
binmode STDOUT, ':utf8';

trim_list([1, 2, 3, 2, 3, 4], 3);
trim_list([1, 7, 2, 8, 3, 9, 4, 10], 5);

sub trim_list {
    
    my ($input, $i) = @_;
    
    say qq[\nInput:  \@n = (] . join(', ', @$input) . qq[), \$i = $i];
    say qq[Output:      (] . join(', ', grep { $_ > $i } @$input) . ')';
}

4 lines of code
Completed after the closing date and not submitted to GitHub

Output from script


Input:  @n = (1, 2, 3, 2, 3, 4), $i = 3
Output:      (4)

Input:  @n = (1, 7, 2, 8, 3, 9, 4, 10), $i = 5
Output:      (7, 8, 9, 10)

 

Any content of this website which has been created by Peter Campbell Smith is in the public domain