Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine

Re: loop to remove negatives

by Athanasius (Chancellor)
on May 15, 2012 at 04:31 UTC ( #970557=note: print w/replies, xml ) Need Help??

in reply to loop to remove negatives

Hi BluGeni,

You should prefer the more idiomatic syntax in Eliya’s solution.

Just thought I’d mention that the code snippet you give, which you say “doesn’t seem to do the job,” should actually work fine, except that there’s a semicolon missing after $i=0; in the for loop:

#!/usr/bin/perl use strict; use warnings; my @busi = ( -1, -42, 7, -17 ); for (my $i = 0; $i < @busi; $i++) { $busi[$i] =~ s/-//g; print "\$busi[$i] = $busi[$i]\n"; } __END__

Gives me:

$busi[0] = 1 $busi[1] = 42 $busi[2] = 7 $busi[3] = 17

as required.


Athanasius <°(((><contra mundum

Replies are listed 'Best First'.
Re^2: loop to remove negatives
by dsheroh (Prior) on May 15, 2012 at 09:53 UTC
    The code given in the OP would work fine, provided that all the values are in an array (@busi). If they're independent scalars ($busi1, $busi2, etc., as in the example of what currently works), then it won't.

    BluGeni, I strongly recommend putting your values into an array, then using

    for (@busi) { $_ =~ s/-//g; }
    (or, more idiomatically, s/-//g for @busi;) instead of working with the variables as independent scalars - any time you have a series of variables named $foo1, $foo2,..., that's a pretty strong indication that what you really want is an array.

    If you need help getting these values into an array, just show us the code that you're currently using to assign their values and we can show you how to modify it to use an array instead.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://970557]
[usemodperl]: greetings
[usemodperl]: question
[usemodperl]: perldoc -v 'ARGV' works but perldoc -v "STDIN' does not, but they are both filehandles. is there a perldoc for STDIN?
[usemodperl]: (typo not withstanding :)
usemodperl thinks about loose coupling...

How do I use this? | Other CB clients
Other Users?
Others cooling their heels in the Monastery: (6)
As of 2018-06-19 19:17 GMT
Find Nodes?
    Voting Booth?
    Should cpanminus be part of the standard Perl release?

    Results (114 votes). Check out past polls.