Philip Stefanov Philip Stefanov - 3 months ago 20
Perl Question

Perl regex expand variable and die if file does not exist

i Found this line:

perl -p -i -e 'BEGIN{ -f $ARGV[0] or die"no file" } s/foo/bar/'
non-existent-file.txt


And i would like to make it work for my case. Expand variables inside the substitution but im not familiar with Perl syntax at all :)

perl -i -0777 -pe 'BEGIN{ -f $ARGV[0] or die".HEAD file is missing" }'
"s|^\\Q${repo}:\\E.+$|${newrepo}|gm" .HEAD;


.HEAD file is missing at -e line 1.
BEGIN failed--compilation aborted at -e line 1.

Answer

Don't generate a Perl code in a shell script!!!

perl -i -pe'
   BEGIN {
      $repo    = shift(@ARGV);
      $newrepo = shift(@ARGV);

      open(my $fh, '<', $ARGV[0])
         or die("Can't open $ARGV[0]: $!\n");
   }
   s|^\Q$repo:\E.+$|$newrepo|g;
' "$repo" "$newrepo" .HEAD

or

export repo
export newrepo
perl -i -pe'
   BEGIN {
      open(my $fh, '<', $ARGV[0])
         or die("Can't open $ARGV[0]: $!\n");
   }
   s|^\Q$ENV{repo}:\E.+$|$ENV{newrepo}|g;
' .HEAD

or

repo="$repo" newrepo="$newrepo" perl -i -pe'
   BEGIN {
      open(my $fh, '<', $ARGV[0])
         or die("Can't open $ARGV[0]: $!\n");
   }
   s|^\Q$ENV{repo}:\E.+$|$ENV{newrepo}|g;
' .HEAD

Notes:

  • The file can exist even if -f returns false. The actual error is in $!. Using open is even more accurate at checking if the file can be opened than -f.

  • I added line breaks added for readability. Remove them if you want, but there's no need to do so.

  • I removed the useless -0777, and the /m that became useless as a result.

Comments