-
-
Save mvasilkov/1643231 to your computer and use it in GitHub Desktop.
postfix to infix
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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