2

I am new to the perl scripting. I am writing script to read excel file and put in text file in C programing syntax.

So I excel sheet I have string like below:

If ((Myvalue.xyz == 1) Or (Frmae_1.signal_1 == 1)) Then a = 1
else a = 0;

This I have to convert into:

a = (((Myvalue.xyz == 1) || (Frmae_1.signal_1 == 1))?1:0)

How this can be handled in perl?

10
  • From what I understand that should work. Here is a website with some information on that tutorialspoint.com/perl/perl_conditions.htm
    – Joe W
    Commented Jun 24, 2013 at 12:51
  • Here is another question on stack overflow with a similar question that might help. stackoverflow.com/questions/9009/…
    – Joe W
    Commented Jun 24, 2013 at 12:54
  • Not sure what are you looking for, my $a = 1 * ($val1 == 1 || $val2 == 1);?
    – mpapec
    Commented Jun 24, 2013 at 13:09
  • @mpapec Why would you multiply by 1? Commented Jun 24, 2013 at 13:13
  • 1
    @HunterMcMillen it will be 1 or empty string for boolean
    – mpapec
    Commented Jun 24, 2013 at 13:30

3 Answers 3

8

I do not think that throwing a regex at the code string would be an especially good idea.The syntax of your input doesn't look too extraordinary, so we could just parse it with Marpa, using a grammar like

:default    ::= action => [values]
:start      ::= StatementList
:discard    ~   ws

StatementList ::= <Expression>+ separator => <op semicolon> bless => Block

Expression ::=
        ('(') Expression (')')  assoc => group action => ::first
    |   Number                  bless => Number
    ||   Ident                  bless => Var
    ||  Expression  ('==')  Expression  bless => Numeric_eq
    ||  Expression  ('=' )  Expression  bless => Assign
    ||  Expression  ('Or')  Expression  bless => Logical_or
    ||  Conditional

Conditional ::=
        ('If') Expression ('Then') Expression
            bless => Cond
    |   ('If') Expression ('Then') Expression ('Else') Expression
            bless => Cond

Ident   ~ ident
Number  ~ <number int> | <number rat>

word    ~ [\w]+
ident   ~ word | ident '.' word
<number int> ~ [\d]+
<number rat> ~ <number int> '.' <number int>
ws      ~ [\s]+
<op semicolon> ~ ';'

Then:

use Marpa::R2;
my $grammar = Marpa::R2::Scanless::G->new({
    bless_package => 'Ast',
    source => \$the_grammar,
});
my $recce = Marpa::R2::Scanless::R->new({ grammar => $grammar });
$recce->read(\$the_string);
my $val = $recce->value // die "No parse found";
my $ast = $$val;

As soon as we have the AST, compiling it down to the C-like representation isn't overly complex. Factoring out the common assignment with an “optimization” pass can be done with a bit of thinking.

However, showing how this can be done is rather lengthy, so I put all the in-depth stuff into this blogpost. We can then define a method that recurses through the tree and emits the C-like code, e.g.

package Ast::Var;
...;
sub compile { my $self = shift; $self->name } # no modification needed

package Ast::Logical_Or;
...;
sub compile {
  my $self = shift;
  # C's "||" operator, plus parens to specify precedence
  "(" . $self->l->compile . "||" . $self->r->compile . ")";
}

package Ast::Cond;
...;
sub compile {
  my $self = shift;
  return sprintf '(%s ? %s : %s)',
      $self->cond->compile,
      $self->then->compile,
      $self->else->compile;
}

etc. for all the other AST node types.

0

The same expression is valid in Perl (modulo the access operator, that -> in perl and not the dot. You can also do

a = $my_value->xyz == 1 || $frmae_1->signal_1 == 1 ? 1 : 0;

the ? 1 : 0 part is not even necessary since $my_value->xyz == 1 || $frmae_1->signal_1 == 1 will return the Perl true or false values (numerically 1 and 0, string '1' and '')...

0

Say, your string is stored in $str. You can do the following to extract stuff from it:

my ($cond, $set, $then, $else) = ($str =~ /^If (.*) Then (.*?=\s+)(.*) else \2(.*);$/);

Now you have your condition in $cond, a = in $set and what should be in that variable in $then and $else.

Replace "or" and "and" in your condition

$cond =~ s/\sOr\s/ || /g;
$cond =~ s/\sAnd\s/ && /g;

and print your desired output

print "$set($cond ? $then : $else);

Those regular expressions work with your string: I got

a = (((Myvalue.xyz == 1) || (Frmae_1.signal_1 == 1)) ? 1 : 0)

but can fail if your actual strings have "Then" written as "then", will explode if your "Myvalue.xyz" in some string is "Myvalue.And" or something like that. Also this will not work if there are no spaces somewhere around = or Or. But the code can be easily modified to work with all these inputs. Be careful with regular expressions, they are powerful.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.