Search code examples
perlperl-data-structures

Perl to exec a program with arguments containing "@"


Am a newbie in Perl and need help with a small problem

Situation:

  1. I have to execute a command line program through perl.
  2. The arguments to this command line are email addresses
  3. These email addresses are passed to me through another module.

Problem:

I have written the code to create the argument list from these email addresses but am having problem in running exec().

NOTE: If I pass hardcoded strings with escaped "@" character to the exec() as command args,it works perfectly.

  1. Sub creating cmd args map

    sub create_cmd_args {
        my($self, $msginfo) = @_;
        my @gd_args_msg  = ('--op1');
        my $mf = $msginfo->sender_smtp;
        $mf =~ s/@/\\@/ig; ## Tried escaping @, incorrect results.
        push @gd_args_msg, '-f="'.$mf.'"';
    
        for my $r (@{$msginfo->per_recip_data}) {
        my $recip = $r->recip_addr_smtp;
        $recip =~ s/@/\\@/ig; ## Tried escaping @, incorrect results.
        push @gd_args_msg, '-r="'.($recip).'"';
      }
      return @gd_args_msg;
    }
    
  2. Sub that uses this args map to exec the program

    sub check {
      my($self, $msginfo) = @_;
      my $cmd = $g_command;
      my @cmd_args = create_cmd_args($self, $msginfo);
      exec($cmd, @cmd_args); ### ******* fails here
    }
    
  3. Sample run:

    INPUT:
      sender_smtp: <ashish@isthisreal.com>
      receiver_smtp: <areyouarealperson@somedomain.com>
    

Could someone please guide me what is wrong here?


Solution

  • As an argument to a command in the shell,

    -f="<ashish@isthisreal.com>"
    

    causes the the string

    -f=<ashish@isthisreal.com>
    

    to be passed to the program. Your program passes

    -f="<ashish\@isthisreal.com>"
    

    to the program. The problem isn't the @; the problem is the " and \ you are adding.

    my $mf = $msginfo->sender_smtp;
    push @gd_args_msg, "-f=$mf";   # Assuming $mf is <ashish@isthisreal.com>