Created
January 19, 2012 19:40
-
-
Save Ky6uk/1642100 to your computer and use it in GitHub Desktop.
infix to postfix
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 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