Skip to content

Instantly share code, notes, and snippets.

@Ky6uk Ky6uk/i2p.pl
Created Jan 19, 2012

Embed
What would you like to do?
infix to postfix
#!/usr/bin/env perl
use strict;
use warnings;
do { print "USAGE: $0 <infix.txt> [postfix.txt]\n"; exit 0 }
unless $ARGV[0];
# output handler
open my $fh_out, '>', ($ARGV[1] || 'postfix.txt') or die $!;
my ($char, @stack);
open my $fh, '<', $ARGV[0] or die $!;
while ( (read $fh, $char, 1) != 0 ) {
( $char =~ /\d/ ) ?
print $fh_out $char :
&do_something
}
close $fh;
print $fh_out pop @stack while defined $stack[-1];
close $fh_out;
# реализация алгоритма Дейкстра (только +, -, *, /)
sub do_something {
if ( not defined $stack[-1] or $char eq '(' ) {
push @stack, $char
}
elsif ( $char eq ')' ) {
while ($stack[-1] ne '(') {
print $fh_out pop @stack;
}
pop @stack
}
elsif ( $char eq '*' or $char eq '/' ) {
while ( $stack[-1] eq '*' or $stack[-1] eq '/' ) {
print $fh_out pop @stack
}
push @stack, $char
}
elsif ( $char eq '+' or $char eq '-' ) {
print $fh_out pop @stack while (
defined $stack[-1] and (
$stack[-1] eq '+' or
$stack[-1] eq '-' or
$stack[-1] eq '*' or
$stack[-1] eq '/'
));
push @stack, $char
}
}
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.