user3534255
user3534255

Reputation: 147

Extract tar.gz file using Perl script

I am doing a Perl script about extracting tar.gz file with specified location but when I run this code of mine.

  use strict;
  use warnings;

  use Archive::Tar;
  use File::Spec::Functions qw(catdir);

  my $input = "sample.tar.gz";
  my $tar   = Archive::Tar->new($input);
  my @files = $tar->list_files;

  my $output_dir = '/var';
  foreach my $file (@files) {

my $extracted_file = catdir($output_dir, $file);
$tar->extract_file($file, $extracted_file);

if ($file =~ /\.rpm\z/ /\.sh\z/ /\.gz\z/) {
    open my $fh, '<', $extracted_file or do { warn "$0: Can't open file $file: $!"; next };
    while (defined(my $line = <$fh>)) {
         do something with $line
                 }
                         close $fh;
                             }
                             }

the file name of my script is "extract.pl" so when I run this script. I got this error

 ./extract.pl: line 1: use: command not found

 ./extract.pl: line 2: use: command not found

 ./extract.pl: line 4: use: command not found

 ./extract.pl: line 5: syntax error near unexpected token `('

 ./extract.pl: line 5: `use File::Spec::Functions qw(catdir);'

Can anyone help me this out ?

Upvotes: 3

Views: 2213

Answers (3)

PradyJord
PradyJord

Reputation: 2160

Please give perl interpreter in first line using

#!/usr/bin/perl

or any path in which perl is installed

Or executed the script as

perl extract.pl

Your script is being interpreted inside your default shell which I believe is bash

so it’s not able to recognize use as there is no such keyword/command in bash or any shell. hence the error

use command not found

Upvotes: 1

mahnkong
mahnkong

Reputation: 355

A shebang ist missing, telling which interpreter should be used by your script.

Please add:

#!/bin/perl

at the first line.

Upvotes: 0

Elliott Frisch
Elliott Frisch

Reputation: 201429

You have two options; One) the first line of your script should be (to search the PATH first) #!/usr/bin/env perl or directly to the path of your perl install (mine is at #!/usr/bin/perl).

Finally, Two) by invoking your script with perl

perl extract.pl

Upvotes: 2

Related Questions