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

In reply to Re^3: Searching and replacing using perl by GrandFather
in thread Searching and replacing using perl by ravimartha

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.