Peter’s blog ✴ Week 107 ✴ 5 April 2021

THE WEEKLY CHALLENGE
Self-descriptive methods

The Perl Camel

Task 2

List methods

Write a script to list the methods of a package/class.

Examples


Example 1
Input:
package Calc;
use strict;
use warnings;
sub new { bless {}, shift; }
sub add { }
sub mul { }
sub div { }
1;
Output:
BEGIN
mul
div
new
add

Analysis

This is a little outside my comfort zone, but a little web searching leads to the conclusion that for package Alpha::Beta the desired result is keys{%{'Alpha::Beta::'}). I hope that's right.

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: Data::Dumper
Note: This will only work if the package is installed on my webserver

Script


#!/usr/bin/perl

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

use v5.26;    # The Weekly Challenge - 2021-04-05
use utf8;     # Week 107 - task 2 - List methods
use warnings; # Peter Campbell Smith
binmode STDOUT, ':utf8';
use Encode;
require URI::Escape;
require Time::Local;

list_methods('URI::Escape');
list_methods('Time::Local');

sub list_methods {
    
    my ($package);
    
    # initialise
    $package = $_[0];
    say qq[\nInput: $package];
    no strict 'refs';
    
    # show details
    say qq[Output: \n  ] . join(qq[\n  ], sort keys %{$package . '::'});
}

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

Output from script


Input: URI::Escape
Output: 
  BEGIN
  EXPORT
  EXPORT_OK
  VERSION
  _fail_hi
  escape_char
  escapes
  import
  uri_escape
  uri_escape_utf8
  uri_unescape

Input: Time::Local
Output: 
  BEGIN
  EXPORT
  EXPORT_OK
  ISA
  SECS_PER_DAY
  SECS_PER_HOUR
  SECS_PER_MINUTE
  VERSION
  _daygm
  _is_leap_year
  _timegm
  timegm
  timegm_modern
  timegm_nocheck
  timegm_posix
  timelocal
  timelocal_modern
  timelocal_nocheck
  timelocal_posix

 

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