Thank you for your help jeffa!
I am a beginner for perl. My new hash keys I can read in from a file, but my values I have to get them from my main hash.Why you use shift? Does it mean it can change different filename everytime you call sub? if it is so, that is what I want.
Please help
| [reply] |
You are most welcome. Yes, that is exactly why i use
shift. shift returns the first value from an array, in
this case it is the implied array @_ which is used by
Perl to store the arguments passed to a given subroutine.
I could have used this instead:
my $filename = shift @_;
# or even
my ($filename) = @_;
# multiple arguments are best caught this way:
my ($first,$second,$third) = @_;
# but some folks prefer
my $first = shift;
my $second = shift;
my $third = shift;
Most (if not all...)
other languages use an argument list to specify what a
subroutine can be 'passed', as well as a return type
(together these form the 'signature'). For example, in
Java, these:
| [reply] [d/l] [select] |
Thank you so much jeffa!
I do make my sub hash, it gave me all the result, but it still tell me :
Use of uninitialized value at ./lx line 97.
Use of uninitialized value at ./lx line 97.
total 10 times Use of above context.
my sub like:
sub create_hash {
my $myhashname=shift;
my %myhashname=%_;
my @keys=@_;
unless(open(FH, ">$myhashname") ) {
print STDERR "Cannot open file\"$myhashname\"\n\n";
exit;}
@myhashname{@keys}=@mydnahash{@keys};
while (($k, $v)=each %myhashname){
print FH "$k=>$v, "};
close FH;
return %myhashname;
}
and I call sub like:
my %myeditedhash=
create_hash('myeditedhash',@editedsites, @mydnahash{@editedsites});
print FH "$k=>$v, "}; is line 97.what is wrong? please help. | [reply] [d/l] [select] |
use strict;
my @array1 = (1,2,3,4);
my @array2 = (5,6,7,8);
my %hash = (
key => 'val',
foo => 'bar',
);
print '=' x 20, "\nwrong way:\n";
wrong1(@array1,@array2);
sub wrong1 {
my (@a1,@a2) = @_;
print "array 1: @a1\n";
print "array 2: @a2\n";
# notice that @a2 is empty
}
print '=' x 20, "\nright way:\n";
right1(\@array1,\@array2);
sub right1 {
my @a1 = @{ shift @_ };
my @a2 = @{ shift @_ };
print "array 1: @a1\n";
print "array 2: @a2\n";
# multiple arrays must be passed in as references
}
print '=' x 20, "\nwrong way:\n";
wrong2(%hash);
sub wrong2 {
my %hash = %_;
while (my($k,$v) = each %hash) {
print "$k => $v\n";
}
# %_ is not special, use @_ instead - always!
}
print '=' x 20, "\nright way:\n";
right2(%hash);
sub right2 {
my %hash = @_;
while (my($k,$v) = each %hash) {
print "$k => $v\n";
}
# a hash is really just a special kind of array
# and yes, multiple hashes must be passed as references too
}
# last - a hash slice
my %slice;
@slice{@array1} = @array2;
print '=' x 20, "\nhash slice:\n";
while (my($k,$v) = each %slice) {
print "$k => $v\n";
}
# and don't creat hash slices inside an subroutine's
# argument list - that is bad bad bad ;)
Good luck, and please read this book: Learning Perl.
jeffa
Cargo Cult Programming - Just say 'NO!' | [reply] [d/l] |