Perl glob strange behaviour -


i have piece of perl code:

if (glob("$data_dir/*$archivefrom*")) {     $command1 = "zip -r -t -m $backup_dir/$archivefrom.zip $data_dir/*$archivefrom*";      $err_cmd1 =system("$command1");     if ($err_cmd1 != 0){print "error $command1\n";exit 1;} } 

sometimes if returns true zip not match anything, why happen? there no concurrent processes remove files in meantime, it's glob returning different zip archive match files, returns non-empty result though should empty.

the glob function in scalar context becomes iterator, not test file existence! can demonstrated following code:

use feature 'say'; @patterns = ('{1,2,3}', 'a', 'b', 'c'); $pattern (@patterns) {   $item = glob $pattern;   $item // "<undef>"; } 

output:

1 2 3 <undef> 

that is, glob remembers first pattern given, iterates on matches, not use new patterns given until iterator exhausted. therefore in expression glob("$data_dir/*$archivefrom*"), updated values in $data_dir , $archivefrom variables not recognized. 1 undef return value @ end of possibilities. if branch isn't executed.

to test if @ least 1 file matching pattern exists, have fetch matches @ once, avoiding iteration. use list context that. use pseudoperator ()= count number of matches – ≥ 1 fine. can assign first match variable, , use in system command, avoid shell interpolation issues:

use autodie ':system'; # automatic error handling, additionally requires ipc::system::simple  if (my ($archivepath) = glob "$data_dir/*$archivefrom*") {   system 'zip', '-r', '-t', '-m', "$backup_dir/$archivefrom.zip", $archivepath; } 

Comments

Popular posts from this blog

html - How to style widget with post count different than without post count -

How to remove text and logo OR add Overflow on Android ActionBar using AppCompat on API 8? -

IIS->Tomcat Redirect: multiple worker with default -