Hi all,

I have encountered a code like this in a production program I couldn't make run:

use strict; use warnings; my $ref_file = $ARGV[0]; if (isReadableFile ($ref_file)) { executeComm ("cat $ref_file"); } else { print STDERR "$ref_file Does not exist\n"; } ## In a different module... sub isReadableFile { my $file = shift; if (defined ($file) && # was a file name passed? ((-f $file) || (-l $file)) && # is the file a file or sym. link +? (-r $file) # is the file readable? ) { return 1; } else { return 0; } } sub executeComm { my ($comm) = @_; print "$comm\n"; system ($comm); print "$?\n"; }

A sample invocation should be something like:

$ perl test.pl file.txt

And if file.txt exists, is a regular file or links to a file and is readable, the command cat file.txt is executed inside the executeComm sub.

The problem arises when the file name or its path contains spaces:

$ perl test.pl file\ name.txt

This should be a valid invocation, but executeComm will receive the command cat file name.txt, and consequently, will fail. The same would happen if $ perl test.pl 'file name.txt' is passed, and perl test.pl 'file\ name.txt' would succeed, but the file tests on isReadableFile fail

A possible patch would be to escape every space after the file tests:

if (isReadableFile ($ref_file)) { $ref_file =~ s/ /\\ /g; ###### Added executeComm ("cat $ref_file"); } else { print STDERR "$ref_file Does not exist\n"; }

But this seems a weak patch... Is this solution portable? Do you anticipate the appearance of more problems?, how would you solve this in production code?

citromatik


In reply to Passing commands to subroutines by citromatik

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.