So we have two posts telling dmtelf that (s)he has to have the filename first in the argument list (not true). We have one post stating that dmtelf can pass an array reference to keep the arguments in the same order -- this is not why an array reference is passed. The following would allow him to preserve his argument order:
Everyone is suggesting alternatives, but that seems so natural that I'm surprised it wasn't brought up. The only reason I mention this is that some shops have may have a standard that the filename comes last in an argument list or perhaps dmtelf was updating a function that is in a library that is required into many programs. If either of those were the case, we wouldn't necessarily have the luxury of changing the order of arguments.$writefile = pop; @arraytowrite = @_;
Also, though several people have corrected this, I don't see that it has been explicitly mentioned. @AllFileDetails[0] should be written as $AllFileDetails[0] with a '$' instead of an '@'. You're referencing a scalar here and Perl prefers that you use the scalar notation. What @AllFileDetails[0] actually does is take a one element array slice, which for all practical purposes is useless (and I suspect that it will have a negative impact on performance).
dmtelf, if you are not used to passing a reference to an array, it is used to speed processing and save memory. What happens is that rather than passing the entire array to the subroutine, Perl (when passing a reference), just passes a value telling the sub where the array can be found. If you have an array with hundreds of elements, passing the reference is much faster. The main danger is that changing array elements in the passed array will now change the elements in the original array also. To actually get at the values in the array that was passed be reference, use the arrow '->' operator. Here's an example:
Cheers,#!/usr/bin/perl -w use strict; # Always use this!!! my @AllFileDetails; $AllFileDetails[0] = "blah, blah, blah"; $AllFileDetails[1] = "foo, bar, diddledum"; print "Printing array.\n"; print @AllFileDetails; print "\nCalling subroutine now\n"; &WriteToDisk(\@AllFileDetails, "garbage", "more garbage", "files.txt") +; print $AllFileDetails[1]; # This will print the new value exit; sub WriteToDisk { my $arraytowrite = $_[0]; my $writefile = pop; print "\nInside the subroutine 'WriteToDisk' now.\n"; print "Printing array.\n"; print $arraytowrite->[0] . " " . $arraytowrite->[1]; $arraytowrite->[1] = "New value\n"; # We've now changed the val +ue of $AllFileDetails[1]! print "\n" . $writefile . "\n"; }
In reply to RE: Weird array printing/passing to subroutine problem
by Ovid
in thread Weird array printing/passing to subroutine problem
by dmtelf
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |