in reply to Re: Searching and replacing using perl
in thread Searching and replacing using perl

ThnQ GrandFather.... i had a query, even the expressions can in different order the output should be same. example: following expressions d = ~f; f = e | c; e = a & b; should give output d = ~((a & b) | c) once again ThanQ....
  • Comment on Re^2: Searching and replacing using perl

Replies are listed 'Best First'.
Re^3: Searching and replacing using perl
by GrandFather (Saint) on Apr 01, 2012 at 11:58 UTC

    The following should work for any systems of expressions that aren't cyclic. It allows multiple dependent expressions as shown by the additional g expression.

    use strict; use warnings; use Graph; my $file = <<FILE; e = a & b; f = e | c; d = ~f; g = ~f | e; FILE open my $fIn, '<', \$file or die "Can't open file: $!\n"; my %subst; my $dag = Graph->new(); while (<$fIn>) { chomp; s/;$//; my ($lhs, $rhs) = split /\s*=\s*/, $_, 2; my %verticies = map {$_ => 1} $rhs =~ /\b(\w+)\b/g; $subst{$lhs} = $rhs; for my $vertex (keys %verticies) { $dag->add_edge($lhs, $vertex) if ! $dag->has_edge ($lhs, $vert +ex); } } die "Expression set contains cycles. Can't process it\n" if ! $dag->is +_dag(); my %roots = map {$_ => 1} $dag->source_vertices(); my %sinks = map {$_ => 1} $dag->sink_vertices(); while (keys %sinks) { my $sink = (keys %sinks)[0]; delete $sinks{$sink}; for my $pred ($dag->predecessors($sink)) { $sinks{$pred} = 1; $subst{$pred} =~ s/\b$sink\b/($subst{$sink})/g if exists $subs +t{$sink}; } } print "$_ = $subst{$_}\n" for sort keys %roots;

    Prints:

    d = ~((a & b) | c) g = ~((a & b) | c) | (a & b)
    True laziness is hard work