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

i want the following comamnd to be written in perl script.How can do it in perl?
find /path/to/files -name '*.csv' | cpio -pdm /target

Replies are listed 'Best First'.
Re: How to write the perl script for the following linux command?
by davido (Cardinal) on Mar 14, 2017 at 14:25 UTC

    Are find and cpio unavailable to you? If you have something that works, but simply need to incorporate it into a larger script, you can use the qx{} operator or `backticks`, or system to execute the external calls.

    While it's a good practice to invoke external calls as infrequently as practical, it's also a good practice to have a clear goal in refactoring, and to leave things that work as they are unless the clear goal necessitates the refactor.

    Writing more code to re-implement the existing solution is just likely to introduce new bugs. On the other hand, if you've decided that the need to re-implement is justified for clearly defined reasons, by all means, File::Find is your first step.


    Dave

      This is good advice overall!

      For the OP, I just wanted to add that there are "better" alternatives to system and backticks. In this particular case, if there are no variables being interpolated into the command string, meaning it's safe enough to call the shell, IPC::System::Simple's run would probably be easiest, since it's just a replacement for system with better error handling.

      use IPC::System::Simple qw/run/; run q{ find /path/to/files -name '*.csv' | cpio -pdm /target };

      Otherwise, e.g. if variables are being interpolated into the command, things can get more complicated - I wrote about the whole topic at length here.

Re: How to write the perl script for the following linux command?
by Corion (Pope) on Mar 14, 2017 at 11:41 UTC

    Can you please also describe in English what this command is supposed to do?

    Most likely, File::Find and File::Copy implement most of the functionality you will need.

      The above command will find the source location and fetches for (*.csv files) and store the same directory structure at destination.

        So, what Perl code did you write, for example using the modules I mentioned already, and how does it fail to do what you need?

Re: How to write the perl script for the following linux command?
by marto (Archbishop) on Mar 14, 2017 at 11:48 UTC
Re: How to write the perl script for the following linux command? ( File::Find::Rule Path::Tiny )
by beech (Parson) on Mar 15, 2017 at 01:56 UTC

    Hi,

    See File::Find::Rule::Procedural and Path::Tiny

    Write something like

    use File::Find::Rule 'find'; my @files = find( -name => '*.csv', -in => $sourcedir ); for my $infile ( @files ){ my( $rel ) = path( $infile )->relative( $sourcedir ); my $outfile = path( $targetdir, $rel ); $outfile->touchpath; path($infile)->copy( $outfile ); }