in reply to Changing a varaibale name within the program?

I first saw the list of $file1, $file2, $file3... And thought "This person needs an array."; Then I saw that you had and array and were for some reason pulling the array into single variables.

If I was doing this I might attack it as such.. (not tested)...

my @user_files = <longfilename>; unshift(@user_files, 'blank'); # skipping to the $ufile line # Make sure $choice is numeric and # within the range in user_files if ( ($choice =~ /^\d+$/) && ($choice > 0) && ($choice <= scalar(@user_files)) ) { file_mod($user_files[$choice], $mail_flag); } else { # Error condition, choice outside of range }
In cases where you are tempted to name things foo1, foo2, foo3... you should take a second look at using an array, because it will likely serve you well. In this case you already were, but then you went awry and started making pointless variables.
Using an array makes your code more expandable, maintainable, and easier to make more robust.

Replies are listed 'Best First'.
Re: Re: Changing a varaibale name within the program?
by Hofmator (Curate) on Jun 27, 2001 at 15:43 UTC

    there's a small bug in your code, Sifmole:

    ($choice <= scalar(@user_files)) # should be ($choice < scalar(@user_files))
    as you are now asking for the number of array elements after you unshifted the blank element, e.g.
    0 1 2 blank file1 file2
    and scalar(@user_files) = 3 but $user_files[3] is undefined!

    -- Hofmator

Re: Re: Changing a varaibale name within the program?
by Dalin (Sexton) on Jun 26, 2001 at 23:43 UTC
    I'm a little confused on the "blank" in the unshift statement? Should I try "blank" or should this be an actual var of some kind. Sorry for all of the newbie questions. Bradley
    Where ever there is confusion to be had... I'll be there.
      Perl arrays start with an index of 0. That is, the first element of @items can be accessed as $items[0]. Adding a blank element to the start of the array means that if the user requests file 1, you can just say @user_files[$choice] instead of $user_files[$choice - 1].

      I'd rather do $choice - 1, but either way, add a comment to the code noting your choice and why you're doing it:

      # @user_files starts at zero, user choice starts at 1 process($user_files[$choice - 1]);
      That'll make life much easier for the maintainer.
        Thanks guys. I'll try this out as soon as I can. Pesky job gets in the way of coding. I'll let you know how it goes. Thanks again. Bradley
        Where ever there is confusion to be had... I'll be there.