Mocking function of external web call



examples/mock-lwp/lib/MyWebAPI.pm
package MyWebAPI;
use strict;
use warnings;

use LWP::Simple qw(get);

sub new {
    my ($class, $url) = @_;
    my $self = bless {}, $class;
    $self->{url} = $url;
    return $self;
}

sub count_strings {
    my ($self, @strings) = @_;

    my $content = get $self->{url};
    #my $content = LWP::Simple::get $self->{url};

    my %data;
    foreach my $str (@strings) {
        $data{$str} = () = $content =~ /$str/ig;
    }
    return \%data;
}

1;

examples/mock-lwp/bin/count.pl
use strict;
use warnings;

use MyWebAPI;

my ($url, @names) = @ARGV;
die "Usage: URL 1-or-more-EXPRESSION\n" if not @names;

my $myapi = MyWebAPI->new($url);
my $res = $myapi->count_strings(@names);
for my $name (sort keys %$res) {
    print "$name   $res->{$name}\n";
}

perl -Ilib bin/count.pl https://code-maven.com/ perl python Java