Thread Bestimmtes Element im array löschen (21 answers)
Opened by kerstin at 2004-08-19 11:31

Crian
 2004-08-19 13:05
#49391 #49391
User since
2003-08-04
5873 Artikel
ModeratorIn
[Homepage]
user image
Wie wärs einfach mit getestetem Code?

Ich hab einen geschrieben mit zwei verschiedenen Methoden zum Entfernen, einmal mit grep, einmal mit splice:

Code: (dl )
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#!/usr/bin/perl
use strict;
use warnings;
use List::Util qw//;

=pod

=head1 FRAGE VON KERSTIN

   Is es in Perl möglich, in einem dynamischen Array ein bestimmtes element zu löschen?
   Die Stelle an der das Element ist, steht nicht fest.

=cut

my @array = List::Util::shuffle ('Zitrone', 'Apfel', 'Birne', 'Kiwi', 'Pflaume', 'Banane');
# Durch shuffle weiß ich nicht, an welcher Stelle Kiwi ist...
print "Vorher:\n";
print "'$_'\n" for @array;

#
# Möglichkeit 1 mit Grep und zwei Arrays:
#

print "Entferne 'Kiwi' ...\n";

my @ohnekiwi = grep {$_ ne 'Kiwi'} @array;

print "Nachher 1:\n";
print "'$_'\n" for @ohnekiwi;

#
# Möglichkeit 2 mit  splice:
#
my $kiwiindex = -1;
for (0..$#array) { $kiwiindex = $_ if $array[$_] eq 'Kiwi' }

if ($kiwiindex >= 0) {
   splice @array, $kiwiindex, 1;
}
else {
   print "'Kiwi' nicht im Array gefunden\n";
}

print "Nachher 1:\n";
print "'$_'\n" for @array;


Ausgabe (2 Läufe):

Code: (dl )
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
G:\privat\perl\forum>array_minus_element.pl
Vorher:
'Pflaume'
'Apfel'
'Birne'
'Zitrone'
'Banane'
'Kiwi'
Entferne 'Kiwi' ...
Nachher 1:
'Pflaume'
'Apfel'
'Birne'
'Zitrone'
'Banane'
Nachher 1:
'Pflaume'
'Apfel'
'Birne'
'Zitrone'
'Banane'

G:\privat\perl\forum>array_minus_element.pl
Vorher:
'Banane'
'Zitrone'
'Pflaume'
'Birne'
'Apfel'
'Kiwi'
Entferne 'Kiwi' ...
Nachher 1:
'Banane'
'Zitrone'
'Pflaume'
'Birne'
'Apfel'
Nachher 1:
'Banane'
'Zitrone'
'Pflaume'
'Birne'
'Apfel'

G:\privat\perl\forum>


Edit: Oh, während ich den Code geschrieben habe hat Ronnie auch schon die Idee mit grep gezeigt - schade ;-)

Grep ist an dieser Stelle imho schöner, es sei denn das Array ist sehr groß (es wird ja zumindestes kurzzeitig verdoppelt).\n\n

<!--EDIT|Crian|1092906429-->
s--Pevna-;s.([a-z]).chr((ord($1)-84)%26+97).gee; s^([A-Z])^chr((ord($1)-52)%26+65)^gee;print;

use strict; use warnings; Link zu meiner Perlseite

View full thread Bestimmtes Element im array löschen