ravimartha has asked for the wisdom of the Perl Monks concerning the following question:

I have some expressions in a file: e = a & b; f = e | c; d = ~f; I need to resolve these expressions into a compound expression like this: d = ~ ((a & b) | c) How can I do this in Perl. Are there any CPAN modules that I can use for this? Or, can this be done without using modules? I am working on a verilog parser project.

Replies are listed 'Best First'.
Re: Searching and replacing using perl
by GrandFather (Saint) on Mar 31, 2012 at 10:34 UTC

    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
      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
Re: Searching and replacing using perl (Verilog)
by toolic (Bishop) on Mar 31, 2012 at 13:29 UTC