There are two major ways to ask the question "Does this string start with S?" in Perl. One method is to use a regular expression. The other is to use substr.
#!/usr/bin/perl
use strict; # glad to see you using strict. Good job!
use warnings; # lexical warnings are better the the -w switch,
# becuase you can turn them off where appropriate.
# Good job using warnings, too.
use diagnostics; # diagnostics give verbose explanations of error mess
+ages.
# It can be very handy when you are just starting out
+.
# You had: open FNAMES,"</var/tmp/flist";
# I made several changes here:
# * I switched to the 3 argument open. It's avoids some potential
# security issues, and is generally considered to be the best
# way to go.
# * I am also using a lexical filehandle instead of a global handle.
# This is generally considered to be the best way to go as well,
# for the same reasons that we prefer lexical variables with
# limited scope to global variables.
# * Finally, I am checking the results of the open() call. If the
# call fails I end the program and display an error message.
open( my $filenames, '<', '/var/tmp/flist' )
or die "Unable to open file list - $!\n";
while ( defined( my $fname = <$filenames> ) ) {
chomp ($fname); # Added a semicolon
# Regex based approaches:
# Does the string start with an "s"?
if ( $fname =~ /^s/ ) {
$fname =~ s/^s/_S/; # Do the substitution
# Do special stuff
}
# Did we replace a starting 's' with '_S'?
if ( $fname =~ s/^s/_S/ ) {
# Do special stuff if we did a substitution.
}
# Using substr()
#
# Does the string start with an "s"?
if ( 's' == substr($fname, 0, 1) ) {
substr($fname, 0, 1) = '_S'; # Do the substitution
# or
substr($fname, 0, 1, '_S'); # Do the substitution
# Do special stuff
}
# Does the string start with an "s"?
if ( 's' == substr($fname, 0, 1) ) {
substr($fname, 0, 1) = '_S'; # Do the substitution
# or
substr($fname, 0, 1, '_S'); # Do the substitution
# Do special stuff
}
}
For this situation, I'd just do the substitution with a regex in the condtional test: if ($fname =~ s/^s/_S/) .... In fact, in most cases a regex is the way to go for looking into strings and finding stuff inside them. But sometimes substr is the way to go.
You've made a good start. Keep working, and you will see good results.
|