Skip to content

Instantly share code, notes, and snippets.

@Ky6uk
Created January 19, 2012 19:40
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Ky6uk/1642100 to your computer and use it in GitHub Desktop.
Save Ky6uk/1642100 to your computer and use it in GitHub Desktop.
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