[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: % with perl



On Mon, Jun 18, 2001 at 01:24:28AM +0000, Robin Gerard wrote:
> this script runs fine:
> 
> #!/usr/local/bin/perl
> 
> print "\n\n";
> %loginpsswd=("gerard","12345678","jaimie","78945612","andy","45632178");

for clarity, you should usually write hash-list expressions
with the => operator:

	%loginpwd = (
		gerard => "1234",
		jaimie => "2468",
		andy   => "9999",
	);

it's a little more clear that you've got key/values pairs, and
it provides some quoting to the left side of the "=>" so you
often don't need to quote them yourselves (but it never hurts to
do so -- and perl may gripe about barewords looking like perl
keywords)...

>  print $loginpsswd{"gerard"};
>  print "\n\n";
>  print $loginpsswd{"jaimie"};
>  print "\n\n";
>  print $loginpsswd{"toto"};
>  print "\n\n";
>  
>  
> but when instead of the six last lines I write:
> 
> $i=0;
> while ($i<3)
> {
> print $loginpsswd{"$loginpasswd[2*$i]"};  
> print "\n\n";
> }
> I get error ...

%something -> hash (record, indexed by field names)
@something -> array (numbered list of items)
$something -> scalar (single value: numeric, string)

$something{key} -> scalar value looked up from a hash/record
$something[ix] -> scala value looked up from an array

inside a "double-quoted" string, perl looks for patterns
that look like representations of variables, which can get
pretty complex -- but there's no math allowed within a
string (not without some @{[]} voodoo, anyway) so you
can't say

	$x=3;
	print "$x*2 nor 2*$x";
		# -> generates "3*2 nor 2*3" not "6 nor 6"

you're looking for something like

	foreach $user ( keys %loginstuff ) {
		print "$user : $loginstuff{$user}\n";  # or
		prnit $user," : ",$loginstuff{$user},"\n";
	}

or

	for ( ($k,$v) = each( %logingunk ) ) {
		print "$k : $v\n";
	}

try

	perldoc -f each
	perldoc -f keys

the camel book and the llama book are both wonderful resources
(for perl and for programming in general) at www.oreilly.com

-- 
DEBIAN NEWBIE TIP #10 from Will Trillich <will@serensoft.com> 
:
Looking to run a command or two at REGULAR INTERVALS?  Try
"crontab -e" for starters (see "man cron" or "man crontab").
You might also investigate the "anacron" package.

Also see http://newbieDoc.sourceForge.net/ ...



Reply to: