Tag: Reddit

  • Frenemies part 2: What a difference a (Perl) module makes

    Frenemies part 2: What a difference a (Perl) module makes

    Last week I explored using the Inline::Perl5 mod­ule to port a short Perl script to Raku while still keep­ing its Perl depen­den­cies. Over at the Dev.to com­mu­ni­ty, Dave Cross point­ed out that I could get a bit more bang for my buck by let­ting his Feed::Find do the heavy lift­ing instead of WWW::Mechanize​’s more general-​purpose parsing.

    A lit­tle more MetaCPAN inves­ti­ga­tion yield­ed XML::Feed, also main­tained by Dave, and it had the added ben­e­fit of obvi­at­ing my need for XML::RSS by not only dis­cov­er­ing feeds but also retriev­ing and pars­ing them. It also han­dles the Atom syn­di­ca­tion for­mat as well as RSS (hi dax­im!). Putting it all togeth­er pro­duces the fol­low­ing much short­er and clear­er Perl:

    #!/usr/bin/env perl
    
    use v5.12; # for strict and say
    use warnings;
    use XML::Feed;
    use URI;
    
    my $url = shift @ARGV || 'https://phoenixtrap-com.us.stackstaging.com';
    
    my @feeds = XML::Feed->find_feeds($url);
    my $feed  = XML::Feed->parse( URI->new( $feeds[0] ) )
        or die "Couldn't find a feed at $url\n";
    
    binmode STDOUT, ':encoding(UTF-8)';
    say $_->title, "\t", $_->link for $feed->entries;

    And here’s the Raku version:

    #!/usr/bin/env raku
    
    use XML::Feed:from<Perl5>;
    use URI:from<Perl5>;
    
    sub MAIN($url = 'https://phoenixtrap-com.us.stackstaging.com') {
        my @feeds = XML::Feed.find_feeds($url);
        my $feed  = XML::Feed.parse( URI.new( @feeds.first ) )
            or exit note "Couldn't find a feed at $url";
    
        put .title, "\t", .link for $feed.entries;
    }

    It’s even clos­er to Perl now, though it’s using the first rou­tine rather than sub­script­ing the @feeds array and leav­ing off the the $_ vari­able name when call­ing meth­ods on it—less punc­tu­a­tion noise often aids read­abil­i­ty. I also took a sug­gest­ed exit idiom from Raku devel­op­er Elizabeth Mattijsen on Reddit to sim­pli­fy the con­tor­tions I was going through to exit with a sim­ple mes­sage and error code.

    There are a cou­ple of lessons here:

    • A lit­tle more effort in mod­ule shop­ping pays div­i­dends in sim­pler code.
    • Get feed­back from far and wide to help improve your code. If it’s for work and you can’t release as open-​source, make sure your code review process cov­ers read­abil­i­ty and maintainability.