Question 6: Another Perl solution
#!/usr/bin/perl
use strict;
use warnings;
use IO::Socket::SSL qw();
use HTML::Grabber;
use WWW::Mechanize;
use List::Util qw(max);
use 5.014;
my $mech = WWW::Mechanize->new(ssl_opts => {
SSL_verify_mode => IO::Socket::SSL::SSL_VERIFY_NONE,
verify_hostname => 0,
});
$mech->get('https://codewars.nzpug.org/spreadsheet/question-001');
sub MAX {
my ($string) = @_;
return max(split(/\s*,\s*/, $string));
}
while (1) {
say $mech->uri;
my $dom = HTML::Grabber->new(html => $mech->content);
my $formula = $dom->find('[name="formula"]')->attr('value');
my $data = parse_data($dom);
print $formula;
$formula =~ s/([A-Z])(\d+)/$data->{$2}{$1}/eg;
$formula =~ s/SQRT\((.*)\)/$1**0.5/eg;
$formula =~ s/MAX\((.*)\)/MAX($1)/eg;
print ' => ', $formula, ' => ', eval($formula);
say '';
$mech->submit_form(with_fields => {
solution => eval $formula,
});
}
sub parse_data {
my $dom = shift;
my $data = {};
my $row = 0;
$dom->find('tr')->each(sub {
my $tr = shift;
my $cell = 'A';
$tr->find('td')->each(sub {
my $td = shift;
$data->{$row}{$cell} = $td->text;
$cell++;
});
$row++;
});
return $data;
}