Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask

syntax of touch a file

by hweefarn (Acolyte)
on Dec 13, 2003 at 08:34 UTC ( [id://314508] : perlquestion . print w/replies, xml ) Need Help??

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

hi everybody :)
i would like to know how is the syntax in perl when i want to touch a file?

i try to use
touch "a.txt";
but not successful.
so, how is the correct syntax?

Thank you very much :)
hav a nice day :)


Replies are listed 'Best First'.
Re: syntax of touch a file
by grinder (Bishop) on Dec 13, 2003 at 09:52 UTC

    Fascinating question.

    First I tried open OUT, ">> $file" and close OUT but that didn't change the time of the file.

    So I thought a bit, and tried open OUT, ">> $file" and print OUT '' and close OUT; but that didn't work either.

    You could always do a system '/usr/bin/touch', $file but that requires knowing where your external touch program lies.

    Then I read the source code to touch.c, found that it refers to a system call named utimes. Looked up utime in perldoc, and got the answer:

    my $now = time; utime $now, $now, $file;

    This changes both the last access time and last modification time to now.

Re: syntax of touch a file
by zengargoyle (Deacon) on Dec 13, 2003 at 09:53 UTC

    see: perldoc -f utime

    $now = time; utime $now, $now, @filenames; # and/or/maybe utime undef, undef, @filenames;
      Note, that the difference with the system touch (/usr/bin/touch) is that utime will not create an empty file, if target file does not exist. That is not always needed, but it's good to know. :)
      A reply falls below the community's threshold of quality. You may see it by logging in.