Skip to content

Instantly share code, notes, and snippets.

@mvasilkov mvasilkov/p2i.pl forked from Ky6uk/i2p.pl
Created Jan 19, 2012

Embed
What would you like to do?
postfix to infix
#!/usr/bin/env perl
use 5.01;
do { say "USAGE: $0 <postfix.txt>"; exit 0 }
unless $ARGV[0];
# --------------- main -----------------
my (@data, $char, $result, @stack);
&init_data;
while (defined $data[0]) {
( $data[0] =~ /^\d+$/ ) ?
$result = $result . $data[0] :
&do_something;
shift @data;
}
$result = $result . pop @stack while defined $stack[-1];
say "resut: $result";
# -------------- subs -------------------
# реализация алгоритма Дейкстра (только +, -, *, /)
sub do_something {
if ( not defined $stack[-1] or $data[0] eq '(' ) {
push @stack, $data[0];
}
elsif ( $data[0] eq ')' ) {
while ($stack[-1] ne '(') {
$result = $result . pop @stack;
}
pop @stack;
}
elsif ( $data[0] eq '*' or $data[0] eq '/' ) {
while ( $stack[-1] eq '*' or $stack[-1] eq '/' ) {
$result = $result . pop @stack
}
push @stack, $data[0];
}
elsif ( $data[0] eq '+' or $data[0] eq '-' ) {
$result = $result . pop @stack while (
defined $stack[-1] and (
$stack[-1] eq '+' or
$stack[-1] eq '-' or
$stack[-1] eq '*' or
$stack[-1] eq '/'
));
push @stack, $data[0];
}
}
# делаем массив из входящей строки
sub init_data {
open my $fh, '<', $ARGV[0] or die $!;
$data = <$fh>;
$data =~ s/[^\d+\*\-\/\(\)]//g;
while ($data =~ /(.)/g) {
my $char = $1;
if ( defined $data[-1] and $data[-1] =~ /^\d+$/ and $char =~ /^\d+$/) {
$data[-1] = join '', $char, $data[-1];
} else { push @data, $char }
}
close $fh
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.