3
0
mirror of https://github.com/pragma-/pbot.git synced 2024-11-25 05:19:29 +01:00
pbot/lib/PBot/Plugin/FuncSed.pm

66 lines
1.8 KiB
Perl
Raw Normal View History

2020-02-14 07:41:51 +01:00
# File: FuncSed.pm
#
# Purpose: Registers the sed Function
2023-02-21 06:31:52 +01:00
# SPDX-FileCopyrightText: 2020-2023 Pragmatic Software <pragma78@gmail.com>
2021-07-11 00:00:22 +02:00
# SPDX-License-Identifier: MIT
2020-02-14 07:41:51 +01:00
2021-07-14 04:45:56 +02:00
package PBot::Plugin::FuncSed;
use parent 'PBot::Plugin::Base';
2020-02-14 07:41:51 +01:00
2021-06-19 06:23:34 +02:00
use PBot::Imports;
2020-02-14 07:41:51 +01:00
sub initialize($self, %conf) {
2020-02-15 23:38:32 +01:00
$self->{pbot}->{functions}->register(
'sed',
{
desc => 'a sed-like stream editor',
usage => 'sed s/<regex>/<replacement>/[Pig]; P preserve case; i ignore case; g replace all',
subref => sub { $self->func_sed(@_) }
}
);
2020-02-14 07:41:51 +01:00
}
sub unload($self) {
2020-02-15 23:38:32 +01:00
$self->{pbot}->{functions}->unregister('sed');
2020-02-14 07:41:51 +01:00
}
# near-verbatim insertion of krok's `sed` factoid
no warnings;
sub func_sed($self, @rest) {
my $text = "@rest";
2020-02-15 23:38:32 +01:00
my $result = eval {
if ($text =~ /^s(.)(.*?)(?<!\\)\1(.*?)(?<!\\)\1(\S*)\s+(.*)/p) {
my ($a, $r, $g, $m, $t) = ($5, "'\"$3\"'", index($4, "g") != -1, $4, $2);
2020-02-15 23:38:32 +01:00
#print "a: $a, r: $r, g: $g, m: $m, t: $t\n";
#print "text: [$text]\n";
2020-05-02 05:59:51 +02:00
if ($m =~ /P/) {
$r =~ s/^'"(.*)"'$/$1/;
$m =~ s/P//g;
2020-02-15 23:38:32 +01:00
if ($g) { $a =~ s|(?$m)($t)|$1=~/^[A-Z][^A-Z]/?ucfirst$r:($1=~/^[A-Z]+$/?uc$r:$r)|gie; }
else { $a =~ s|(?$m)($t)|$1=~/^[A-Z][^A-Z]/?ucfirst$r:($1=~/^[A-Z]+$/?uc$r:$r)|ie; }
} else {
if ($g) { $a =~ s/(?$m)$t/$r/geee; }
else { $a =~ s/(?$m)$t/$r/eee; }
}
return $a;
2020-02-15 23:38:32 +01:00
} else {
return 'sed: syntax error; usage: sed s/<regex>/<replacement>/[Pig]; P preserve case; i ignore case; g replace all';
2020-02-15 23:38:32 +01:00
}
};
if (my $e = $@) {
$e =~ s/ at .*$//;
return "sed: syntax error: $e";
2020-02-14 07:41:51 +01:00
}
return $result;
2020-02-14 07:41:51 +01:00
}
use warnings;
1;