in reply to Searching and replacing using perl

A quick search of CPAN didn't turn up anything that looks like it deals with bitwise operators for symbolic algebraic manipulation, but for the simple example you give the following works:

use strict; use warnings; use Math::Algebra::Symbols; my $file = <<FILE; e = a & b; f = e | c; d = ~f; FILE open my $fIn, '<', \$file or die "Can't open file: $!\n"; my %subst; my $last; while (<$fIn>) { chomp; s/;$//; my ($lhs, $rhs) = split /\s*=\s*/, $_, 2; $rhs =~ s/(\w+)/exists $subst{$1} ? "($subst{$1})" : $1/ge; $subst{$lhs} = $rhs; $last = "$lhs = $rhs"; } print $last;

Prints:

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

Replies are listed 'Best First'.
Re^2: Searching and replacing using perl
by ravimartha (Initiate) on Apr 01, 2012 at 07:18 UTC
    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....

      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