I've been working through Kernighan and Pike's The Unix Programming Environment as well as Kernighan and Ritchie's The C Programming Language and basically just rewriting c and sh scripts in Perl for practice (and because sometimes I just enjoy finding short Perl scripts to replace more drawn out examples of C).
I wrote the following to take a list of files from the command line and run them through gcc if their filenames qualify. Nothing difficult, but it's nice to finally write a functional piece of code that I can use while I continue learning Perl/C/*nix. I'm hoping to receive input on style (in particular my use of control structures/loops and regex's) and any general coding conventions I may be missing. I'm still a beginner so I fear that in reviewing my own code I may be missing weighty details in my learning.
#!/usr/bin/perl use strict; use warnings; sub getFiles { my @files; my $ex; foreach (@ARGV) { push @files, $_ if (-e $_ && m/.+\.[cC]$/); print "Couldn't Find $_\n" unless (-e $_); print "Invalid file: $_\n" unless (m/^.+\.[cC]$/); } return \@files; } sub compile { my $files = shift; my %table; foreach (@$files) { $table{$_} = substr $_, 0, -2; } `gcc $_ -o $table{$_}` foreach (keys %table); } compile(getFiles);
Is there a "better" way of handling filenames, and their modifications, to be passed to gcc for each file than my use of a hash? I tried to modify the filenames inline as in different combinations of things like:
`gcc $_ -o substr $_, 0, -2` foreach (@$files);
I couldn't get it to work syntactically, and I understand that clarity is sacrificed this way, but I suppose curiosity got the best of me. Is something like this even possible? I couldn't really find anything on Google about calling a Perl function within a Unix function within Perl.
My other question is regarding my use of substr() to remove the .c from the filenames. I tried to use a regex first instead of substr(), but I don't think I'm completely understanding the documentation I've read on using regex's for substitution. If a monk could provide an example for this particular situation to facilitate my learning, it would be greatly appreciated.
Thanks again for any input, and I apologize if this post is unwittingly simplistic.
In reply to Simple Regex Question / Code Review by marquezc329
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |