Walt Mankowski on 19 Apr 2011 08:01:42 -0700

[Date Prev] [Date Next] [Thread Prev] [Thread Next] [Date Index] [Thread Index]

Re: [PLUG] perl -e with system()

On Tue, Apr 19, 2011 at 10:39:58AM -0400, Chris Nehren wrote:
> On Apr 19, 2011, at 10:28 , Randall A Sindlinger wrote:
> > Hey folks,
> > 
> > I'm getting a weird error.
> > 
> > I have a tab-separated datafile of the form
> > 
> > audit-2.0.5-5.8.1.x86_64	/var/log/audit/audit.log
> > ca-certificates-1-9.1.noarch	/var/lib/ca-certificates/ca-bundle.pem
> > filesystem-11.4-11.14.1.x86_64	parent is /boot/	/boot/backup_mbr
> > filesystem-11.4-11.14.1.x86_64	parent is /etc/	/etc/.pwd.lock
> > 
> > I want to split the filenames up into separate files, just using the package
> > as the filename.
> > 
> > perl -n  -e '($a, $b, $c) = split("\t"); chomp $a; chomp $b; chomp $c; if ($c) {system ("echo $c >> $a")} 
> > else {system ("echo $b >> $a")}' < data.file
> The problem is that you're not quoting things properly. The LIST
> form of system does this for you, but it also doesn't invoke a
> subshell (so you can't do >>).

That's not correct.  If system() is passed a single parameter, that's
checked for shell metacharacters, and if any are found, the argument
is passed to "/bin/sh -c".  At least on unix.  Different things will
happen on other platforms.

In fact, Randall's script worked just fine for me and didn't print out
any errors.  My guess is that some of the other records in that file 
might be missing tabs and that's confusing the redirection.

> You really should be using open instead:
> open my $fh, '>>', $file or die "open($file): $!";
> print $fh $content;
> close $fh;

That would certainly be a more robust solution, but it's also making
it a pretty big one-liner...
> Note also that $a and $b are special variables used by perl for
> sort() and you shouldn't use them. See perldoc perlopentut for more
> info, and please consider reading Beginning Perl so you don't make a
> mess of things.

True, you definitely don't want to do that in a real program.  But it
hardly matters in a one-liner where he's clearly not doing any

> > Thanks,
> >         . o 0 ( So _this_ is why I should've gone to JP's talk )
> This has very little to do with the shell and everything with perl.

I'm still voting for bad data. :)


Attachment: signature.asc
Description: Digital signature

Philadelphia Linux Users Group         --        http://www.phillylinux.org
Announcements - http://lists.phillylinux.org/mailman/listinfo/plug-announce
General Discussion  --   http://lists.phillylinux.org/mailman/listinfo/plug